Thakoo
Thakoo

Reputation: 1

C# question about: Do...While Loops (on Unity)

  1. Why does MyInt being increased above 1 whereas the while condition is false?
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.

  1. Then, why do the same code crashes when I set myBool to true from the Inspector? -> whereas I thought myInt would have reached 1 (Q1) and then would go further once (and not before) myBool was set to true from the Inspector.

  2. Why do I feel so dumb just with this Do...While basic?

please excuse my english

Upvotes: 0

Views: 442

Answers (1)

Tech Inquisitor
Tech Inquisitor

Reputation: 343

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.

Upvotes: 1

Related Questions