On Collision Enter Object Variable Acces NullReferenceException

I’m trying to access the stats of an opponent, but there is a nullreferenceexception for the lines defining optype1 and optype2

    function OnCollisionEnter(collision:Collision) 

{

print("hi");

var optype1 = collision.gameObject.GetComponent(BaseStats).type1;

var optype2 = collision.gameObject.GetComponent(BaseStats).type2;

How should I fix it?

You may be having collisions with the ground or other objects that don’t have the script BaseStats. The easiest way to avoid this is to check if the object hit has a BaseStats script:

function OnCollisionEnter(collision:Collision) 
{
  var baseStScript: BaseStats = collision.gameObject.GetComponent(BaseStats);
  if (baseStScript){
    var optype1 = baseStScript.type1;
    var optype2 = baseStScript.type2;
    ...
  }
}