Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Stuck in a forever loop.

Discussion in 'Scripting' started by Nadinya, Nov 8, 2019.

  1. Nadinya

    Nadinya

    Joined:
    Mar 1, 2019
    Posts:
    5
    Hi, I have probably quite a silly question but I am confused about something. A little while ago I created a loop where it would generate a 'random' number every x seconds while the game was running. To begin with I wanted it to start doing this at the start of the game or in the Start method so I wrote

    Code (CSharp):
    1. private void start()
    2. {
    3. while(gameIsRunning){
    4.      StartCoroutine(NumberSpawner());
    5.     }
    6. }

    Anyways something like that. It broke the game of course. So I switched the while loop into the coroutine and it works. But here is my question from my understanding Start only gets called once thats why i put it in there to begin with. How can it create this forever loop?
     
  2. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,469
    It never get out of start because it doesn't end.
    Think about it:
    -call start
    -start call infinite loop
    - game wait for start to end
    - start wait for infinite loop to end
    Waiting for godot take less time
     
    Antypodish and Lethn like this.
  3. Nadinya

    Nadinya

    Joined:
    Mar 1, 2019
    Posts:
    5
    Ah cheers, Yes that makes sense. For some reason my logic seemed to be really off haha