Search Unity

Unity 2D While Loop Keeps Crashing Unity. How to fix?

Discussion in '2D' started by unnameddeveloper, Oct 18, 2019.

  1. unnameddeveloper

    unnameddeveloper

    Joined:
    Oct 13, 2019
    Posts:
    2
  2. unnameddeveloper

    unnameddeveloper

    Joined:
    Oct 13, 2019
    Posts:
    2
    I am trying to make a system where the player's speed gradually increases. I found a way to do this using the fixed update function, however that updates too fast. If there is another way to do this that a beginning developer might understand, then please show me. Thanks for you help!
     
  3. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    That while loop is simply going to repeat over and over within a single frame, thus never getting to the rest of the code and thus never getting to the next frame. It is very important that when using a while loop that something WITHIN the loop will cause the condition to be false and thus exit the loop.

    Try this:

    Code (CSharp):
    1.  
    2.     [SerializeField]
    3.     private float speedIncreasePerSecond;
    4.  
    5.     private float speed;
    6.     private bool moving;
    7.  
    8.  
    9.     void Update()
    10.     {
    11.  
    12.         if(moving)
    13.                     speed += speedIncreasePerSecond * Time.deltaTime;
    14.     }
    15.  
     
    vakabaka likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,455
    As stated above, you've created what is known as an infinite loop and because all these scripts run on the main-thread only, it will lock the engine up (not "crash" it).

    Also, a minor thing, but there's no such thing as Unity 2D. :)
     
  5. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    Code (CSharp):
    1. private void Start()
    2. {
    3. constMove = true;
    4. }
    5.  
    6. private void Update()
    7. {
    8. if(constMove == true)
    9. {
    10. // if you want it to run a check non-stop
    11. Move();
    12. }
    13. // Pretend the above if statement doesn't exist
    14. if(constMove == true)
    15. {
    16. constMove = false;
    17. // Now your code will only run once.
    18. // At the end of your Move function, you would make
    19. // constMove true again if you wanted it to be able to run again
    20. Move();
    21. }
    22. }