- Why does
MyInt
being increased above 1 whereas thewhile
condition isfalse
?
public class HelloStackoverflow : MonoBehaviour {
int myInt = 0;
public bool myBool = false;
void Update () {
print(myInt);
do{
myInt ;
}while(myBool == true);
}
}
-> I expected myInt
to reach 1 and not more cause myBool
is never set to true
. I understood that the Do
part of a Do...While
is being executed at least once before the condition is being checked, to see if it should loop or not.
Then, why do the same code crashes when I set
myBool
to true from the Inspector? -> whereas I thoughtmyInt
would have reached 1 (Q1) and then would go further once (and not before)myBool
was set totrue
from the Inspector.Why do I feel so dumb just with this
Do...While
basic?
please excuse my english
CodePudding user response:
Update
is called more than once. (Every frame, I think. I'm a Unity novice myself.) Every time Update
is called, your do...while
loop runs once, incrementing myInt
. It crashes (or becomes unresponsive) when you set myBool
to true because it never exits the loop.
CodePudding user response:
The answer above is correct, because this field is not in the update method, which is triggered every frame and therefore it is not reset, and the loop that is in the method is executed every time. If you do not want this field to increase, then you should use the usual While loop. Sorry for my English, I used a translator.