- Home /
NullReferenceException | Enable/Disable problem
Hello, I have the following script to enable and disable a gameobject. The first click on the button is ok: the gameobject dissapears. But after the second click I get this error:
NullReferenceException Buttonscript.OnGUI () (at Assets/Myscript.js:5)
This is my script:
function OnGUI(){
if(GUI.Button(Rect(20,20,50,25), "Click it!")){
var object_1=GameObject.Find("myObject");
object_1.SetActiveRecursively(!object_1.active);
}
}
Thanks!
please indent code with 4 spaces each line, mark the code and hit the 01001-button or use htlm tags for better readability, thank you. [I know UnityAnswers formatting-instructions SUC$$anonymous$$]
Answer by SisterKy · Feb 05, 2012 at 07:12 PM
Not sure, but I think you can't find inactive Objects.
Won't the object stay paired with the button or why do you have to do a new search each time you click it? This is also not good performance-wise (Finds are quite expensive operations)
Edit. Just as I said, put the Find in function Start; here's the full script. I hope this works...
var object_1 : GameObject;
function Start(){
object_1=GameObject.Find("myObject");
}
function OnGUI(){
if(GUI.Button(Rect(20,20,50,25), "Click it!")){
object_1.SetActiveRecursively(!object_1.active);
}
}
Thanks, so what should I change? I'm a noob, so I don't know where to start;-)
Uuh... Ok, let's make a deal; effort for effort. ;)
I'll tell you what to change if you fix your formatting in your question.
the edit button is very small at the lower left of your post.
Ok, so did I; edited my answer. Hope this does the trick...
Thanks, but: Assets/$$anonymous$$yscript.js(7,17): BCE0005: $$anonymous$$ identifier: 'object_1'.