- Home /
Toggle GUI button
How does it work the GUI toggle?
I want to be able to switch between two textures if the toggle is on or off.
Answer by runevision · Mar 19, 2010 at 11:21 AM
The GUI.Toggle is described on this page in the manual and here in the scripting reference.
If you want something to happen when toggling the toggle, here is one way to do it:
var toggleBool = true;
function OnGUI () { var toggleBoolNew = GUI.Toggle (Rect (25, 25, 100, 30), toggleBool, "Toggle");
// Check if the toggle was toggled
if (toggleBoolNew != toggleBool) {
if (toggleBoolNew == true)
Debug.Log("Toggle was enabled");
else
Debug.Log("Toggle was disabled");
toggleBool = toggleBoolNew;
}
}
Thanks..now I understand how to activate functions regarding the on/off state of the toggle
== true
could be omitted and consider adding the curly brackets {}
even if you have only one line to execute.. because usually you don't have only one.. for example.. what if you want to add the code for changing the texture and see Debug.Log("Texture was changes")
..
@maveryck21 don't forget to upvote awesome answers.. especially the ones that helped you :)
@Lipis I added == true to make the code more readable - this language construct is not obvious for people new to program$$anonymous$$g, for example. But you're right that it can be left out. About where to use curlies, that is a matter of taste.
@Rune Skovbo Johansen ♦♦
what if I only want to play a sound once using toggle button??because I tried your code and the sound keeps playing...
How do I make it done once??
PROBLE$$anonymous$$ SOLVED : by adding a conditional statement before setting the boolean to true I'm able to set the toggle to play the sound only once.
Your answer
Follow this Question
Related Questions
Switching between set of components 1 Answer
Toggle Switch 6 Answers
How to turn on a light, then off with the same button. 1 Answer
Switch between mouse controller character to controlling camera? 0 Answers
Toggle Scripts On & Off 1 Answer