Access private variable from UI Event

Hey guys, I am trying to use a private variable inside a public function that is used as the Button Click event, but it is not working.

Here is what I have it currently setup:

private GameObject myGameObj;

void Awake(){
    myGameObj = GameObject.Find("game_object_name");
}

// This function works fine, myGameObject becomes inactive
void Start(){
    myGameObj.SetActive(false)
}

public void myFunction(){
    myGameObj.SetActive(true);
}

And in my UI Button, in the click event I am calling myFunction. I know the reference for myGameObj is correct because during the Start event, I am setting it to be inactive and that works just fine. But when I try to make it active again (using a button event) it does not work!

My first though was some issue related to the GameObject be inactive, but I removed the SetActive code and tried to only print the reference using Debug.Log.

Printing it during the Start event shows the right reference. Printing it during the myFunction event shows a null reference.

Any ideas? Thank you!

  1. Are you sure the object is not destroyed between Start and myFunction?
  2. Are you sure the function called is the “correct one” (meaning you don’t have attached the script twice and used the object not calling the Start method)
  3. Are you sure myFunction is not called before Awake (it can happen if the gameObject is not active when the scene starts)

Use Debug.Log to help you find the issue

 private GameObject myGameObj;
 void Awake(){
     myGameObj = GameObject.Find("game_object_name");
     Debug.Log( "myGameObj retrieved : " + myGameObj, myGameObj ) ;
 }
 // This function works fine, myGameObject becomes inactive
 void Start(){
     myGameObj.SetActive(false);
     Debug.Log( name + " is disabling myGameObj", myGameObj ) ;
 }
 
 public void myFunction(){
     myGameObj.SetActive(true);
     Debug.Log( name + " is enabling myGameObj", myGameObj ) ;
 }