Is there a way to modify the NullReferenceException for Unity gameObjects so that not only does it say "object reference not set to an instance of an object," but also says exactly what the name of the object in code that was null?

For example, if I write

GameObject myGameObj,

forget to assign myGameObj in the inspector, and then say


is there a way to print to the Unity console something along the lines of

"Object reference not set to an instance of an object. The object that is null is {0}", $name_of_nullVariable_in_code$);


See: https://docs.unity3d.com/Manual/NullReferenceException.html

  • \$\begingroup\$ I haven't used Unity in a while, but doesn't it tell you exactly what line creates the exception? \$\endgroup\$ – Alexandre Vaillancourt Aug 26 '17 at 22:55
  • \$\begingroup\$ It does, but say you have a very long line or a line of code that takes up 2 or 3 lines of text and there are multiple possible sources of error. Is there a way to further narrow the search? \$\endgroup\$ – reincarnationofstackexchange Aug 26 '17 at 22:57
  • \$\begingroup\$ Aside from splitting your instruction line into many, I don't see any, but maybe someone else will know. \$\endgroup\$ – Alexandre Vaillancourt Aug 26 '17 at 23:03
  • \$\begingroup\$ You could consider putting a break point on the line and step-by-step debug that line until you hit the null reference. \$\endgroup\$ – Alexandre Vaillancourt Aug 26 '17 at 23:03
  • \$\begingroup\$ Usually for the case you describe of an unset Inspector parameter, Unity will throw a custom MissingReferenceException instead, which does tell you the name. If you're getting a NullReferenceException instead, then it's more likely an unset local/unserialized variable or something that's been nulled in code. Unfortunately there's not a lot more info you can capture automatically in that case without stepping into to code as A.V. suggests. All true nulls look alike, and don't bear any metadata about where they came from. (Unity uses fake nulls to give more info for the Missing/Destroyed cases) \$\endgroup\$ – DMGregory Aug 27 '17 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.