- Home /
++ Changes variable to 121?
I know exactly why this is happening. My function is OnGUI. I have my simple script saying that when a button is pressed it adds a variable +1. It adds 121 or some times 50 - it's random. I know why it happens - because it measures how long the button is pressed for. I'm guessing that the "if (GUI.Button..." statement is set for when the mouse it pressed, not let go. Does anyone know how to make it so when you click the button, it adds 1 only???? Thanks!!!
This works:
if (GUI.Button (Rect(10,10,50,50), "Click?"))
Respect +=1;
print(Respect);
This doesn't:
if (GUI.Button (Rect(10,10,50,50), "Click?"))
print(Respect);
Respect +=1;
Answer by perchik · Sep 06, 2013 at 04:32 PM
You need curly braces around an if statement that is more than one line.
if (GUI.Button (Rect(10,10,50,50), "Click?"))
{
print(Respect);
Respect +=1;
}
The first example works because without curly braces, the first line after the if statement is the body of the statement
That is
if (GUI.Button (Rect(10,10,50,50), "Click?"))
Respect +=1; //the if statement applies to this line
print(Respect); //but not this line
but here
if (GUI.Button (Rect(10,10,50,50), "Click?"))
{ //with curly braces
Respect +=1; //the if statement applies to this line
print(Respect); //the if statement applies to this line too
}
Sorry, I actually did have curly braces in it but didn't paste them onto the comment!
So you're saying if you print the variable first, it doesn't get changed?
the variable gets changed (you told it to, by putting Respect +=1
), but if the print happens before the addition then the print will grab the value at that specific point in time, and then the modification will happen. take for example the following examples
if (GUI.Button (Rect(10,10,50,50), "Click?")){
respect = 10
respect += 1;
// respect = 11
print(restect); // console shows 11
}
if (GUI.Button (Rect(10,60,50,50), "Click?")){
respect = 10
print(respect); // console shows 10
respect += 1;
// respect = 11
}
if (GUI.Button (Rect(10,110,50,50), "Click?")){
respect = 10
print(respect); // console shows 10
restpect += 1;
// respect = 11
print(respect); // console shows 11
sometimes it is important to know the value of a variable both before, and after a change (usually for more complex changes, but that is beside the point)
Your answer
![](https://koobas.hobune.stream/wayback/20220613113710im_/https://answers.unity.com/themes/thub/images/avi.jpg)