Why I can't use while to check "hasStarted"

In the video is use if to check “hasStarted” is true or false

    if (!hasStarted)
    {
        LockBallToPaddle();
        LaunchOnMouseClick();
    }

and I just try to use while to change the code like

    while(!hasStarted)
    {
        LockBallToPaddle();
        LaunchOnMouseClick();
    }

when I click play, unity is just stop work.
I want to ask why while can’t work?
Thanks.

Hi Booow.

Welcome to our community! :slight_smile:

while is a loop, and loops get executed until the condition is false. Update() gets called and executed once per frame. The user input gets logged once per frame. The frame ends when all Unity methods were executed. Since the while-loop gets terminated only if the condition is false, the frame will never end, no new user input will logged. Unity ends up in an endless loop, and, eventually, you’ll get a stackoverflow exception error.

Did this make sense?


See also:

Now I understand why it don’t work.
Thanks!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms