NullReferenceException: Object reference not set to an instance of an object

I’ve gotten this error message with the game now, not sure if it was a problem beforehand. What’s weird is that the game will run, and the collision will occur either if Barry hits his head or goes through the finish line (and Barry will return to the start), but the error message pops up if the collision has a reason to trigger a second time. Any ideas? Pretty sure my code is the same as in the tutorial.

My very poor understanding of C# makes me think that a new instance is being created, but isn’t being linked properly to the script somehow.

Unity will give you a bit more information in the console when presenting an error, e.g.

MyFile.cs(10,13): NullReferenceException: Object reference not set to an instance of an object.

That first part tells you which file the error is in, and which line of code. In this example it would be in MyFile.cs line 10. You can use that to narrow down where the error is.

This exception is telling you that a variable is unassigned (its value is nothing or ‘null’). Without seeing your code I couldn’t tell you exactly what’s happening; happy to take a look if you want to post it. One way to avoid the exception is to check it against null, e.g.

if (myVariable == null) 
{
  return;
}

or

if (myVariable != null) {
  //Code that you want to run
}

Hope that helps.

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

Privacy & Terms