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

This is a problem I face so many times that I need to write it as a reminder for my future self.

How to fix Null Reference Exceptions: What does it mean that an object reference is not set to an instance of an object.

Let’s say we have a method we want to call, this function is in script B, and you want to call it from script A.

This may happen for multiple reasons, let’s say we have our UI logic in scriptB and our player input handler in scriptA, in this case would be a simple method that enables/disables a UI screen when we press the ESC key. We don’t want to mix the code together, so from one place we just call the logic in the other.

This will not work:

We’ll get the famous NullReferenceException: Object reference not set to an instance of an object . Why? Because we’re not referencing an Object here, but the script itself at GetComponent<UIElements>();

What we need to do is call the method from an existing Object, in this case for example would be the Canvas. This will work:

The difference here is that we’re getting an Object first with GameObject tempObject = GameObject.Find(“Canvas”); and then we reference the UIElement component on that object, finally calling the method, on that specific object.

Using GameObject.Find() is not the most performant method in Unity but is good enough for the sake of this example, the point is that as long as you reference the object that contains the script first, this won’t be null, and the method you want to call will be available.

Advertisements

Leave a Reply