- Home /
Cases if a GUI.Button is clicked two or more times??
Hi! I'm new in this community, so excuse me if I write something wrong (and if my english is not so good). I wrote a very simple script in C# that create a button (thanks to GUI.Button function) and, if the player clicks on it, a number set before is added to a variable called sum.
Everything works great, but now I want that if the player clicks again on the button, the number is removed from the variable sum, and not added again, and so on (with the third click the number is added, with the fourth is removed, ...). I really thanks who want to help me! :)
if (GUI.Button(new Rect(10,40,100,50), "" + number1)){
somma=somma+number1;
Debug.Log("La somma è: " + somma);
}
Answer by aljovidu · Apr 30, 2014 at 03:29 PM
Hey. You can do this using a boolean variable to track its alternating state.
private bool _isClicked;
void OnGui()
{
if (GUI.Button(new Rect(10,40,100,50), "" + number1))
{
if(!_isClicked)
{
somma += number1;
_isClicked = true;
}
else
{
somma -= number1;
_isClicked = false;
}
Debug.Log("La somma è: " + somma);
}
}
Answer by Nerevar · Apr 30, 2014 at 03:30 PM
Hello,
I hope I got it right, this is what I have for you :
[somewhere in your code]
private bool trigger = true;
private int number1 = ???;
[...]
if (GUI.Button(new Rect(10,40,100,50), "" + number1)){
int op = trigger ? 1 : -1; // when you said you want to remove it once a twice I understood substract it to the sum. I hope it is correct, else replace -1 by 0.
trigger = !trigger;
somma=somma+number1*op; Debug.Log("La somma e: " + somma); }
tell me if it is the behaviour you expect !
regards,