While loop crashing in update but why not if statement?

Anybody able to tell me why this code immediately crashes when using a while loop, yet works fine with the if statement?

void Update()
    {//Tracks players position. Script not attached to player object
       
        playerXPos = player.transform.position.x;
        playerZPos = player.transform.position.z;

  while (playerZPos > 0f) {
            print(playerZPos);
        }
    }

The player’s position can return to below 0.

This is because an if statement will test, pass or fail, and then let the update method end meaning the game can continue to process this frame and move on to the next.

However a while loop if playerPosZ is not immediately <=0 will loop back on itself indefinitely not letting update function end, and thus not letting the game continue to run.

In your case, processing will stay within the WHILE LOOP for as long as the player’s Z is greater than 0f. Because this value never changes within the while loop you never exit this while loop.

When your case is met (playerZPos > 0f) processing enters the loop but can never leave because you have not provided a way for it to exit. Unless there is something within the while loop that adjusts the player’s Z position (i.e. some decrement like ‘playerZPos -= time.deltatime * 1f’). Your loop will continue repeating infinitely as the playerZPos never changes from the value it was when the while loop was entered.

No other processing occurs anywhere else in your application while you are within this loop (other than printing the playerZPos).

While loops are normally used to process lists, arrays, or perform tasks on sets of things. For example, lets say I want to check every X & Y point on an image for something or every inventory item in a list and sum the weights.

To do this we need to increment counters or tests to control when to exit the while loops …

 // Sudocode Warning
 int X = 0;
 int Y = 0;
 bool FoundSomething = false;
 WHILE (X <= image.width && !FoundSomething) {
     X++;
     Y = 0;
     WHILE (Y <= image.height && !FoundSomething) {
          Y++;
          FoundSomething = LookForSomething(X,Y);
     }
} 

This will step through every coordinate, both X and Y, in the image and LookForSomething() in it. Note that as soon as X or Y exceed the image width or height those while loops are exited and code processing moves on. Note also that if the LookForSomething() function returns TRUE (e.g. finds what it was looking for) then we can also exit both while loops.

Bottom line is that one needs to be careful when creating while loops to ensure that they have a reasonable exit point and never loop endlessly.