Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

While loops keep crashing Unity?

Discussion in 'Scripting' started by GamedStars, Sep 2, 2019.

  1. GamedStars

    GamedStars

    Joined:
    Jul 29, 2018
    Posts:
    2
    At first I assumed it was an infinite loop but after adding some pieces of code to insure that it wasn't an infinite loop it still crashes? I know the code right now is better with a for loop but I just want to try out the while loop properly.

    Code (CSharp):
    1. public float speed = 0.1f;
    2. private bool test = true;
    3. int x = 0;
    4.  
    5. // Start is called before the first frame update
    6. void Start(){
    7.     while(test){
    8.         x++;
    9.         Debug.Log(x);
    10.         if(x == 10){
    11.             bool test = false;
    12.         }
    13.     }
    14. }
    I normally code in Python but I wanted to expand my coding skills to C# so I decided to pick up C#, so sorry for any stupid mistakes!
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    you're declaring a new bool(at the local function scope) and setting it to false, the while loop will check the class variable.

    Code (CSharp):
    1. public float speed = 0.1f;
    2. private bool test = true;
    3. int x = 0;
    4. // Start is called before the first frame update
    5. void Start(){
    6.     while(test){
    7.         x++;
    8.         Debug.Log(x);
    9.         if(x == 10){
    10.             test = false;
    11.         }
    12.     }
    13. }
    or just

    Code (CSharp):
    1. public float speed = 0.1f;
    2. private bool test = true;
    3. int x = 0;
    4. // Start is called before the first frame update
    5. void Start(){
    6.     while(x < 10){
    7.         x++;
    8.         Debug.Log(x);
    9.     }
    10. }
     
    GamedStars likes this.
  3. GamedStars

    GamedStars

    Joined:
    Jul 29, 2018
    Posts:
    2
    Thank you!! It works :D