NullReferenceException?

Hi. Just a quick question. I am making a moba in unity and I am getting the NullReferenceException. I don’t understand why. The only reason I can think of is that I had a crash and it now messed up for some reason. The line where the error is is this one: if(canMove == true && inCombat == false && towerScript.towerDestroyed == false)

Thank you for your help.
//Proximal Pyro

If we look at those variables:

  • canMove and inCombat appear to be booleans, so it is unlikely they hold a null value.
  • towerScript appears to be a custom class is is much more likely to be null.

I suggest inserting the following code just above the if condition:

if (towerScript == null) {
    Debug.Log("towerScript is null");
}
else {
    Debug.Log("towerScript is not null");
}

Then you can check the console to confirm this theory.

See DotNetPearls on NullReferenceException (C#) if you want to understand:

  • What NullReferenceException means
  • Why and when they appear
  • How to recover from them

To complement the article, in most cases in Unity, you are probably looking for an object that doesn’t exist, such as:

var pear = appleTree.GetComponent<Pear>();
pear.Eat(); // You don't have a Pear. Pears doesn't exist on Apple Trees.

Or:

var invisibleMan = GameObject.Find("Invisible Man");
invisibleMan.SendMessage("Seen", "Cat Woman");
    // If invisibleMan was not found, it makes no sense 
    // to tell him he's seen Cat Woman.

The fix is to check if you got what you want before trying to use it:

if (pear)
    pear.Eat(); // Safe!
else
    Debug.LogWarning("Didn't find a Pear");

if (invisibleMan)
    invisibleMan.SendMessage("Seen", "Cat Woman"); // Safe!
else
    Debug.LogWarning("That guy is impossible to find!");