- Home /
Creating a GUI Button with more than one case
So here's the deal, I want to create a button that does something when I push it.
var a = 1;
function OnGUI() {
if(GUI.Button (Rect (0,0,20,20), "Click Here") && (a == 1){
a = 2;
}
}
That works just fine, but I want to add a use for the button if a = 2
var a = 1;
function OnGUI() {
if(GUI.Button (Rect (0,0,20,20), "Click Here") && (a == 1){
a = 2;
}
if(GUI.Button (Rect (0,0,20,20), "Click Here") && (a == 2){
a = 1;
}
}
But this gives me two buttons on top of each other. How can I make the button do multiple different things depending on the second conditional I give it? Do I need to use "else if" in some way? Or am I way off? Any help would be appreciated, I'm sure this is simple and I'm just overlooking something.
Answer by robertbu · May 16, 2014 at 04:12 AM
You can reverse the order of the parameters in the 'if' statement:
var a = 1;
function OnGUI() {
if((a == 1) && GUI.Button (Rect (0,0,20,20), "Click Here")){
a = 2;
}
if((a == 2) && GUI.Button (Rect (0,0,20,20), "Click Here")){
a = 1;
}
}
Javascript use short circuit boolean evaluation. That means when the first clause evaluation fails (a == 1), then the rest of the clause is not evaluated. So by switching them, one of the two GUI.Button() calls is not made.
Answer by Clet_ · May 16, 2014 at 04:13 AM
use a switch case inside your if block
if(GUIButton (Rect (0,0,20,20), "Click Here") {
switch(a) {
case 1 :
//Do stuff for a = 1
break;
case 2 :
//Do stuff for a = 2
break;
}
}
Will this work if "a" is equal to a string not an int?
Your answer

Follow this Question
Related Questions
GUI Button Animation Cue 1 Answer
GUI window popup button 1 Answer
Android Button Screen 1 Answer
GUI.Textfield backspace control + Button Style problem 0 Answers
Nothing happens when clicking button 1 Answer