How to properly reference a game object

If I attempt to assign a GameObject to a private variable in Start() or Awake() then access that object I get NullReferenceException.

But if I make it public and assign it via inspector it works fine. What am I doing wrong?


This works if drag and drop the game object into myObject via the inspector.

using UnityEngine;
using System.Collections;


public class ChangeControls : MonoBehaviour {
public GameObject myObject;
    
    void ChangeMyObject()
    {
        myObject.SomeValue = 42;
    }   
}

This however does not work.

 using UnityEngine;
 using System.Collections;
 
 
 public class ChangeControls : MonoBehaviour {
 private GameObject myObject;
     void Start()
    {
        myObject = GameObject.Find("My Object");
    }
     void ChangeMyObject()
     {
         myObject.SomeValue = 42;
     }   
 }

There’s a chance that the line:

myObject = GameObject.Find("My Object");

Is not finding the object. In which case it would be null, of course that can be prevented by using a null check when assigning values.

Additionally, I would try moving your find of the object into an “Awake” method instead of “Start”. This is necessary if your “ChangeMyObject()” method is being invoked before the value is assigned.

Quickly testing this out, using this script:

using UnityEngine;
using System.Collections;


public class ChangeControls : MonoBehaviour
{
    private GameObject myObject;

    void Start()
    {
        myObject = GameObject.Find("My Object");

        if(myObject != null)
        {
            ChangeMyObject();
        }
    }

    void ChangeMyObject()
    {
        Debug.Log("Found!");
    }
}

No errors are returned and it works fine.
This suggests that it’s something else in your script, perhaps ‘myObject.SomeValue’.

Since it works fine if you assign it via inspector, perhaps you could explain more about what this value is, since in the code provided it makes no sense.

I ended up scrapping the script and created a new one from scratch and now it works.

The only thing I can come up with is something (a reference) had to be corrupted in Unity because the new script exactly matches the old one.