How to find a nullref in Unity3D scripting

I am developing a standard “How to handle a nullref” post, since it is the most-common and (usually) simplest form of error encountered when scripting in Unity3D.

Steps to find a Null Reference (nullref) error:

In the console, doubleclick the error to figure out where it is in your code.

What is in that line of code that could be null? (reference types obviously)

Is it a complicated hairy line of code? Then break it down into constituent statements, run it again, find where the error is now

When you know which variable is null, now ask yourself:

  • what mechanism is supposed to set that variable up? (UnityEditor? GetComponent? GameObject.Find()? Something else?)
  • why is it not being set up? (unable to find, misconfigured, something else?)
  • fix it.

You can do this. Trust me.

ALSO: often one nullref begets 999+ more… start with the very first one at the very top of your log, because often it will trigger all the others.


Leave a Reply

Your email address will not be published. Required fields are marked *