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. It is also an error you will see forever into the future as long as you do software engineering. Get really familiar with fixing it.

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.

See http://plbm.com/?p=248 for tips on breaking down hairy code.

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? Code not being called? Setup code called later than access code? Something else?)
  • fix it.

You can do this. Trust me.

ALSO: often the very first nullref begets 999+ more. ALWAYS start with the very first one at the very top of your log, because often it will trigger all the others, which aren’t really an actual problem.

0 Shares

Leave a Reply

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