while loops crash unity

i was trying to make a while loop but it kept on crashing unity, i tried to test it by doing

while(Input.GetKeyDown(KeyCode.F))
{
    Debug.Log("Test");
}

and the game was fine until i pressed F so i’m assuming it crashes unity because it performs this code infinite times in 1 frame (im not 100% cetrain though because i’m pretty new to coding), but I used to be able to use while loops, why did it start crashing all of the sudden?

GetKeyDown is true in the one frame where the key is pressed. Your while loop now encounters this variable as either true or false. When it is true, it will always be true since the while loop cant end until the frame ends and the frame cant end until the loop ends. So the loop ending would be required for the frame to end, which is required for the loop to end. You effectively have an infinite loop here.

For a while-loop this is always the case unless the condition can be changed from within the loop itself.
Just as an example:

// This will end
int i = 0;
while(i < 10)
{
    Debug.Log(i);
    i++; // Since we are affecting the loop condition from within the loop!
}
// This wont stop (and in fact crash the programm)
bool someBool = true;
while(someBool)
{
    Debug.Log("Test");
}
// Since the condition will only change after the loop, which cannot be reached without first ending the loop. Very similar to your situation!
someBool = false;

As for what you are doing… you are likely just intending to use if instead of while there. This would print “Test” once per KeyDown. If you want to print “Test” every frame youd have to use GetKey, instead of GetKeyDown, since the latter is only true for the one frame where the key is pressed down.

1 Like