- Home /
Getting script from another script bug
I need a button that will turn another script (SmoothLookAt) on and off.
Here's my script:
function OnGUI () {
if (GUI.Button (Rect (20,20,90,20), "On/Off Button")) {
GetComponent(SmoothLookAt).enabled = true;
}
else {
GetComponent(SmoothLookAt).enabled = false;
}
}
It works, but scripts turns on only for one moment (When button is clicked). I'm missing something?
Answer by Zerot · Oct 04, 2012 at 04:52 PM
Yes. That is the behaviour you get the way you coded it. GUI.Button returns true if the button is pressed that frame. Which means that most of the time it will be false. This will execute the else, and set enabled to false. So only the frame you clicked it will be true and the next frame(or even quicker depending on what events the OnGUI receives) it will be set to false.
If you want to toggle the boolean, do this:
if (GUI.Button (Rect (20,20,90,20), "On/Off Button")) {
GetComponent(SmoothLookAt).enabled = !GetComponent(SmoothLookAt).enabled;
}
That will flip between the 2 states of the boolean.
Your answer
Follow this Question
Related Questions
GetComponent Help 2 Answers
Get variable from another object 1 Answer
2 Bugs in my game: mouse control takes some time to load and Menu not working. 0 Answers
GUI co-ordinates bug? 1 Answer
how can i get GUI.Button presse(or down not click) 3 Answers