Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved while loops crash unity

Discussion in 'Scripting' started by MrBoogyBam, Mar 13, 2021.

  1. MrBoogyBam

    MrBoogyBam

    Joined:
    Mar 4, 2021
    Posts:
    23
    i was trying to make a while loop but it kept on crashing unity, i tried to test it by doing
    Code (CSharp):
    1. while(Input.GetKeyDown(KeyCode.F))
    2. {
    3.     Debug.Log("Test");
    4. }
    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?
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,606
    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:
    Code (CSharp):
    1. // This will end
    2. int i = 0;
    3. while(i < 10)
    4. {
    5.     Debug.Log(i);
    6.     i++; // Since we are affecting the loop condition from within the loop!
    7. }
    Code (CSharp):
    1. // This wont stop (and in fact crash the programm)
    2. bool someBool = true;
    3. while(someBool)
    4. {
    5.     Debug.Log("Test");
    6. }
    7. // Since the condition will only change after the loop, which cannot be reached without first ending the loop. Very similar to your situation!
    8. 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.
     
    Last edited: Mar 13, 2021
    mopthrow likes this.