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!
Answer by Hellium · Nov 28, 2018 at 10:00 AM
Are you sure the object is not destroyed between
Start
andmyFunction
?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)Are you sure
myFunction
is not called beforeAwake
(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 ) ;
}
Thank you, that did the job! For some reason the function reference got swapped. It was pointing to the prefab ins$$anonymous$$d of the GameObject in scene.
Your answer
Follow this Question
Related Questions
public vs private array in classes 0 Answers
Building Scripts on each other 1 Answer
Custom geometry image hover 0 Answers
Triggering UI button onmousedown, without waiting for mouseup event? 1 Answer