Var in GUI button - strange but true!

Hi All,

I am showing a page increment counter on a GUI. The code below doesn’t work properly:

@script ExecuteInEditMode
var message = “Instructions”;
var counter1: int;
var counter2 : int;
var pagecount : int;

function OnGUI () {
GUI.Label(Rect(120, 20, 140, 25), message+" "+pagecount);
if (GUI.Button(Rect(320, 20, 70, 15), “Next”)) {
pagecount ++;

}
if (GUI.Button(Rect(10, 20, 70, 15), “Previous”)) {
pagecount --;

}
print("Counters: " + counter1 + ", " + counter2 + ", " + pagecount);
}

while this code DOES!!

@script ExecuteInEditMode
var message = “Instructions”;
var counter1: int;
var counter2 : int;
var pagecount : int;

function OnGUI () {
GUI.Label(Rect(120, 20, 140, 25), message+" "+pagecount);
if (GUI.Button(Rect(320, 20, 70, 15), “Next”)) {
pagecount ++;
counter1 ++;
}
if (GUI.Button(Rect(10, 20, 70, 15), “Previous”)) {
pagecount --;
counter2 --;
}
print("Counters: " + counter1 + ", " + counter2 + ", " + pagecount);
}

Can someone explain to me why? It appears in the first example that there are 2 instances of pagecount, one for each button as when you press the button an appropriate number of times pagecount then continues to increment or decrement. But why does adding the unique counter variable to each button allow pagecount to work as a single instance (i.e as expected)?

With thanks, Peter

OnGUI may be called more than once per frame (for different reasons–layouting, painting, etc).

Not sure what you mean…in both cases, clicking on “next” makes pagecount go up, and clicking on “previous” makes it go down. A button is only called once no matter how many times OnGUI runs per frame; it can only return true again when the mouse button is let go of and clicked again.

–Eric

Hi Eric,

Try code sample one. Press the increment button 5 times and pagecount will increment.

Then press the decrement button. Not until you press it 5 times will pagecount actually decrement, then it does decrement by 5.

You can see the decrement button depressing, but pagecount doesn’t change until it reaches the initial value on the decrement button, then it shows as decreasing from that value!

Cheers, Peter

I did try it before I wrote my message. :slight_smile: You don’t have multiple copies of the script running or something?

Edit: Never mind; you’ve got “collapse” on in the console. Turn it off. :wink:

–Eric

Bloody BRILLIANT !

Thanks for that. I have spent hours trying to explain this artifact and couldn’t.

So thanks again Eric for your help,

Regards, Peter

Don’t worry, you’re by far not the first person who’s wasted time because of this. I’ve said it before: they really ought to have that off by default…

–Eric