- Home /
How to toggle GameObject visibility?
Hi, I have the following code:
function OnGUI(){
if(GUI.Button(Rect(10,10,50,30), "Button1")){
var object1=GameObject.Find("An object");
object1.SetActiveRecursively(true);
}
}
But every time I click the button it should show/hide/show/hide. How can I do this? What I tried:
function OnGUI(){
if(GUI.Button(Rect(10,10,50,30), "Button1")){
var object1=GameObject.Find("An object");
if(!object1){
object1.SetActiveRecursively(true);
}else{
object1.SetActiveRecursively(false);
}
}
}
Thanks for the help!
Answer by Berenger · Feb 04, 2012 at 11:23 PM
This is because SetActiveRecursively(false) does not set the variable object1 to null, you would have an exception otherwise. Try that :
if( /* blabla button */ )
object1.SetActiveRecursively( !object1.active );
Also, find that object once and for all in you Start function. It's a slow process, you don't want to run it each time.
Thanks, this is my code now: function OnGUI(){
if(GUI.Button(Rect(10,10,180,20), "Landbouwers uitbreiding")){
var object1=GameObject.Find("Landbouwers mess");
print(object1.active);
object1.SetActiveRecursively(!object1.active);
}
}
But I get this error:
NullReferenceException Switch_script.OnGUI () (at Assets/Switch_script.js:5)
Your answer
![](https://koobas.hobune.stream/wayback/20220613063737im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Toggle Button Question 0 Answers
Cases if a GUI.Button is clicked two or more times?? 2 Answers
Using GUIToggle to on/off buttons! 5 Answers
How do I reset a objects position through a GUI Button ? 1 Answer
UI Button Instead of OnGUI Button? 1 Answer