Null reference

the null reference is annoying me every time maybe beginner like me suffers too

Null pointers were invented by a man named Tony Hoare in the 60s as a convenience. Sadly, over 50 years later, we’re still suffering the consequences for the decision. Tony Hoare famously called it “The billion dollar mistake” (due to the lost productivity in eliminating null reference errors). Personally, I think he underestimated the value.

It’s important to check anything that could possibly be null before acting on it… at this point, this mostly includes object references. I’ll give an example as one of the null references that always seems to happen while creating the fighter script…

void Update()
{
     bool inRange = Vector3.Distance(transform.position, target.transform.position)<3;
     if(target!=null && inRange)
     {
           GetComponent<Mover>().MoveTo(target.transform.position);
     }
}

Note that it looks like we have done a null check here if(target!=null) but in fact, we have already acted on target before the statement. In this case, a simple if(target==null) return; at the beginning of the method would completely eliminate a null reference.

As you progress, you’ll get better and better at spotting these potential null references. As this is an intermediate series, we don’t always remind you of these checks, but they’re needed nonetheless.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms