GameObject find returns null outside Start method

I’m attempting to access a method from a different script. I’m getting the information in the Start method, assigning the GameObject find/get component script code to a variable. When I’m printing the results inside the Start method, it prints the correct gameobject/script. However, outsie the Start method it returns null, even though the variable is public.

My code:

 void Start()
        TestScript STScript = GameObject.Find("TestObject").GetComponent<TestScript>();
        print(STScript); // Prints TestObject(TestScript)

    void OnTriggerEnter2D(Collider2D collider)
        print(STScript); // Prints null

What am I doing wrong?


Is your code exactly as posted? The reason I ask is that I’m surprised you’re not getting any errors… your STScript doesn’t exist in the scope of your OnTriggerEnter() method. As Graham has pointed out, you need to declare your STScript variable outside of your Start() method, then assign the component to it in Start() and it will all work as intended :slight_smile: