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.
/* ScriptA.cs */
if (Something){
// Call method located in ScriptB.cs
ScriptB.MyMethod();
}
/* ScriptB.cs */
public void MyMethod(){
// Do something
}
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:
/* ScriptA.cs : Player Input Handler */
if (Input.GetKeyDown(KeyCode.Escape))
{
var menu = GetComponent<UIElements>();
menu.ToggleMenu();
}
/* ScriptB.cs : UI Elements */
public void ToggleMenu() {
if (isPauseMenuActive == false)
{
pauseMenu.gameObject.SetActive(true);
isPauseMenuActive = true;
}
else
{
pauseMenu.gameObject.SetActive(false);
isPauseMenuActive = false;
}
}
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:
/* ScriptA.cs : Player Input Handler */
if (Input.GetKeyDown(KeyCode.Escape))
{
GameObject tempObject = GameObject.Find("Canvas");
var menu = tempObject.GetComponent<UIElements>();
menu.ToggleMenu();
}
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.
Leave a Reply