CTIN 289 - Interactive Snippets Library

Powered by 🌱Roam Garden

Null References

When your code instantiates a new thing, you can keep a reference to the new thing like this

GameObject newGO = Instantiate(missilePrefab);

The newGO will point to that new missile, for as long as it exists.

If you do this in Player.cs:

GameObject newGO = Instantiate(misslePrefab);

And then the missile, unbeknownst to you, is destroyed, then the variable newGO will still exist, but it will point to nothing, or null. It's like calling a phone number that has been disconnected.

// If you try to get to a thing that has been destroyed, for example like this:

Debug.Log(newGo.name);

// What you are doing is asking nothingness(null) for its name. By definition, nothingness does not have a name. SO you will get a Null Reference Exception
// This is such a popular error that it has a nickname: NullRef. 
// So how can you prevent NullRefs? You must litter your code with null checks, like this:

if(newGO != null)
{
  Debug.Log(newGo.name);
}