Why am I not getting stuck in the loopWhy does this Unity code work as expected only with the while loop?StopCoroutine is not stopping my coroutine in UnityPut a coroutine on potentially infinite loopWhy doesn't this coroutine consistently finish?IEnumerator Loop not Drawing Changes to Transform.positionInfinite loop ping test for each playerDisplay loading screen after scene change but wait for coroutine to finishWhy even use coroutines in Unity?Starting Couroutine in newly activated gameObjectIs coroutine as good as a delay() function

London underground zone 1-2 train ticket

Will a research paper be retracted if the code (which was made publically available ) is shown have a flaw in the logic?

Ubuntu show wrong disk sizes, how to solve it?

Do some languages mention the top limit of a range first?

Why do dragons like shiny stuff?

What is it exactly about flying a Flyboard across the English channel that made Zapata's thighs burn?

How to deactivate the username quickly

Based on what criteria do you add/not add icons to labels within a toolbar?

Is there a way to prevent the production team from messing up my paper?

Why is the Vasa Museum in Stockholm so Popular?

Did silent film actors actually say their lines or did they simply improvise “dialogue” while being filmed?

Probably terminated or laid off soon; confront or not?

Repeated! Factorials!

What date did Henry Morgan capture his most famous flagship, the "Satisfaction"?

How do I get the =LEFT function in excel, to also take the number zero as the first number?

Could an areostationary satellite help locate asteroids?

Is there a way to improve my grade after graduation?

Plato and the knowledge of the forms

What is an air conditioner compressor hard start kit and how does it work?

Is space radiation a risk for space film photography, and how is this prevented?

Can attackers change the public key of certificate during the SSL handshake

How easy is it to get a gun illegally in the United States?

How do I show and not tell a backstory?

Did Captain America make out with his niece?



Why am I not getting stuck in the loop


Why does this Unity code work as expected only with the while loop?StopCoroutine is not stopping my coroutine in UnityPut a coroutine on potentially infinite loopWhy doesn't this coroutine consistently finish?IEnumerator Loop not Drawing Changes to Transform.positionInfinite loop ping test for each playerDisplay loading screen after scene change but wait for coroutine to finishWhy even use coroutines in Unity?Starting Couroutine in newly activated gameObjectIs coroutine as good as a delay() function






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3












$begingroup$


I'm new to Unity. I was learning coroutines and I wrote this.
enter image description here



When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?









share









New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 9




    $begingroup$
    Please copy and paste your code into a snippet instead of a picture.
    $endgroup$
    – Evorlor
    8 hours ago










  • $begingroup$
    I just recently got back into Unity myself, I notice that the Input methods are taking in a string "Fire1", is that something you can set up in the engine to allow for key remappings rather than typing out Keycode.Foo?
    $endgroup$
    – Mkalafut
    5 hours ago






  • 1




    $begingroup$
    It might help to realize that yield is effectively short for "Yield control to the caller until the next item in the Enumerable is requested."
    $endgroup$
    – 3Dave
    5 hours ago

















3












$begingroup$


I'm new to Unity. I was learning coroutines and I wrote this.
enter image description here



When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?









share









New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 9




    $begingroup$
    Please copy and paste your code into a snippet instead of a picture.
    $endgroup$
    – Evorlor
    8 hours ago










  • $begingroup$
    I just recently got back into Unity myself, I notice that the Input methods are taking in a string "Fire1", is that something you can set up in the engine to allow for key remappings rather than typing out Keycode.Foo?
    $endgroup$
    – Mkalafut
    5 hours ago






  • 1




    $begingroup$
    It might help to realize that yield is effectively short for "Yield control to the caller until the next item in the Enumerable is requested."
    $endgroup$
    – 3Dave
    5 hours ago













3












3








3


2



$begingroup$


I'm new to Unity. I was learning coroutines and I wrote this.
enter image description here



When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?









share









New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I'm new to Unity. I was learning coroutines and I wrote this.
enter image description here



When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?







unity c# coroutines





share









New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share









New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







share



share








edited 6 hours ago









Joe

1807 bronze badges




1807 bronze badges






New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 9 hours ago









babybrainbabybrain

161 bronze badge




161 bronze badge




New contributor



babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




babybrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • 9




    $begingroup$
    Please copy and paste your code into a snippet instead of a picture.
    $endgroup$
    – Evorlor
    8 hours ago










  • $begingroup$
    I just recently got back into Unity myself, I notice that the Input methods are taking in a string "Fire1", is that something you can set up in the engine to allow for key remappings rather than typing out Keycode.Foo?
    $endgroup$
    – Mkalafut
    5 hours ago






  • 1




    $begingroup$
    It might help to realize that yield is effectively short for "Yield control to the caller until the next item in the Enumerable is requested."
    $endgroup$
    – 3Dave
    5 hours ago












  • 9




    $begingroup$
    Please copy and paste your code into a snippet instead of a picture.
    $endgroup$
    – Evorlor
    8 hours ago










  • $begingroup$
    I just recently got back into Unity myself, I notice that the Input methods are taking in a string "Fire1", is that something you can set up in the engine to allow for key remappings rather than typing out Keycode.Foo?
    $endgroup$
    – Mkalafut
    5 hours ago






  • 1




    $begingroup$
    It might help to realize that yield is effectively short for "Yield control to the caller until the next item in the Enumerable is requested."
    $endgroup$
    – 3Dave
    5 hours ago







9




9




$begingroup$
Please copy and paste your code into a snippet instead of a picture.
$endgroup$
– Evorlor
8 hours ago




$begingroup$
Please copy and paste your code into a snippet instead of a picture.
$endgroup$
– Evorlor
8 hours ago












$begingroup$
I just recently got back into Unity myself, I notice that the Input methods are taking in a string "Fire1", is that something you can set up in the engine to allow for key remappings rather than typing out Keycode.Foo?
$endgroup$
– Mkalafut
5 hours ago




$begingroup$
I just recently got back into Unity myself, I notice that the Input methods are taking in a string "Fire1", is that something you can set up in the engine to allow for key remappings rather than typing out Keycode.Foo?
$endgroup$
– Mkalafut
5 hours ago




1




1




$begingroup$
It might help to realize that yield is effectively short for "Yield control to the caller until the next item in the Enumerable is requested."
$endgroup$
– 3Dave
5 hours ago




$begingroup$
It might help to realize that yield is effectively short for "Yield control to the caller until the next item in the Enumerable is requested."
$endgroup$
– 3Dave
5 hours ago










5 Answers
5






active

oldest

votes


















7












$begingroup$

When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in.



I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on what coroutines are and how powerful they can be.



This blog and searching youtube post was also helpful for me to better use coroutines.






share|improve this answer








New contributor



David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





$endgroup$






















    3












    $begingroup$

    Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this:



    class FireContinuouslyData 
    int state;
    bool shouldBreak;


    object FireContinuously(FireContinuouslyData data)
    switch (data.state)
    case 0:
    goto State_0;

    while (true)
    GameObject laser = ...;
    laser.GetComponent...
    //the next three lines handle the yield return
    data.state = 0;
    return new WaitForSeconds(fireTime);
    State_0:




    And internal to Unity/C# (since yield return is a native c# feature), when you call StartCoroutine, it creates a FireContinuouslyData object, and pass it in to the method. Based on the return value, it determines when to call it again later, simply storing the FireContinuouslyData object to pass it in next time.



    If you ever did a yield break, it could internally just set data.shouldBreak = true and then Unity would simply throw away the data and not schedule it again.



    And if there were any data that needed to be saved between executions, it would also be stored in the data for later.



    An example of how Unity/C# might implement the coroutine functionality:



    //Internal to Unity/C#

    class Coroutine
    Action<object> method;
    object data;


    Coroutine StartCoroutine(IEnumerator enumerator)
    object data = CreateDataForEnumerator(method); //Very internal to C#
    Action<object> method = GetMethodForEnumerator(enumerator); //Also very internal to C#
    Coroutine coroutine = new Coroutine(method, data);
    RunCoroutine(coroutine);
    return coroutine;


    //Called whenever this coroutine is scheduled to run
    void RunCoroutine(Coroutine coroutine)
    object yieldInstruction = coroutine.method(coroutine.data);
    if (!data.shouldBreak)
    //Put this coroutine into a collection of coroutines to run later, by calling RunCoroutine on it again
    ScheduleForLater(yieldInstruction, coroutine);







    share|improve this answer











    $endgroup$






















      1












      $begingroup$

      Another answer mentions that you are stopping co-routines when "Fire1" is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of "Fire1".



      In your case however this code will not become 'stuck' in an infinite loop, which is what it looks like you're looking for an answer to - i.e. the while(true) loop, even if you did not stop it externally.



      It won't get stuck but your coroutine won't end (without calling StopCoroutine() or StopAllCoroutines()) either. This is because Unity coroutines yield control to their caller. yielding is different to returning:



      • a return statement will cease execution of a function, even if there is more code following it

      • a yield statement will pause the function, starting at the next line after yield when resumed.

      Usually, coroutines will be resumed each frame but you're also returning a WaitForSeconds object.



      The line yield return new WaitForSeconds(fireTime) roughly translates as "now suspend me, and don't come back until fireTime seconds have passed".



      IEnumerator FireContinuously()

      // When started, this coroutine enters the below while loop...
      while(true)

      // It does some things... (Infinite coroutine code goes here)

      // Then it yields control back to it's caller and pauses...
      yield return new WaitForSeconds(fireTime);
      // The next time it is called , it resumes here...
      // It finds the end of a loop, so will re-evaluate the loop condition...
      // Which passes, so control is returned to the top of the loop.




      Unless stopped, this is a coroutine which, once started, will perform the whole loop once every fireTime seconds.






      share|improve this answer









      $endgroup$






















        1












        $begingroup$

        A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you yield return) using the IEnumerator that your function returns.



        Since you use the yield keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work?



        It is lazy and doesn't generate all the collection at once (and the collection may be infinite and impossible to be generated at once). Elements of the collection are generated as needed. Your function returns an iterator for Unity to work with. It calls its MoveNext method to generate a new element and Current property to access it.



        So your loop isn't endless, it runs some code, returns an element and returns control back to Unity so it's not stuck and can do other work such as handling your input to stop the coroutine.






        share|improve this answer









        $endgroup$






















          1












          $begingroup$

          The reason is the keyword yield which has a specific meaning in C#.



          On encountering the words yield return a function in C# returns, as one would expect.




          Using yield to define an iterator removes the need for an explicit extra class



          [...]



          When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.




          So there is no infinite loop. There is a function/iterator that can be called an infinite number of times.



          The Unity function StartCoroutine() makes the Unity framework call the function/iterator once per frame.



          The Unity function StopAllCoroutines makes the Unity framework stop calling the function/iterator.



          And returning WaitForSeconds(time) from the iterator makes the Unity framework suspend calling the function/iterator for time.






          share|improve this answer









          $endgroup$

















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "53"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );






            babybrain is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgamedev.stackexchange.com%2fquestions%2f174390%2fwhy-am-i-not-getting-stuck-in-the-loop%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            7












            $begingroup$

            When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in.



            I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on what coroutines are and how powerful they can be.



            This blog and searching youtube post was also helpful for me to better use coroutines.






            share|improve this answer








            New contributor



            David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





            $endgroup$



















              7












              $begingroup$

              When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in.



              I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on what coroutines are and how powerful they can be.



              This blog and searching youtube post was also helpful for me to better use coroutines.






              share|improve this answer








              New contributor



              David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.





              $endgroup$

















                7












                7








                7





                $begingroup$

                When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in.



                I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on what coroutines are and how powerful they can be.



                This blog and searching youtube post was also helpful for me to better use coroutines.






                share|improve this answer








                New contributor



                David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                $endgroup$



                When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in.



                I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on what coroutines are and how powerful they can be.



                This blog and searching youtube post was also helpful for me to better use coroutines.







                share|improve this answer








                New contributor



                David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.








                share|improve this answer



                share|improve this answer






                New contributor



                David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.








                answered 9 hours ago









                David WeatherheadDavid Weatherhead

                712 bronze badges




                712 bronze badges




                New contributor



                David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.




                New contributor




                David Weatherhead is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.




























                    3












                    $begingroup$

                    Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this:



                    class FireContinuouslyData 
                    int state;
                    bool shouldBreak;


                    object FireContinuously(FireContinuouslyData data)
                    switch (data.state)
                    case 0:
                    goto State_0;

                    while (true)
                    GameObject laser = ...;
                    laser.GetComponent...
                    //the next three lines handle the yield return
                    data.state = 0;
                    return new WaitForSeconds(fireTime);
                    State_0:




                    And internal to Unity/C# (since yield return is a native c# feature), when you call StartCoroutine, it creates a FireContinuouslyData object, and pass it in to the method. Based on the return value, it determines when to call it again later, simply storing the FireContinuouslyData object to pass it in next time.



                    If you ever did a yield break, it could internally just set data.shouldBreak = true and then Unity would simply throw away the data and not schedule it again.



                    And if there were any data that needed to be saved between executions, it would also be stored in the data for later.



                    An example of how Unity/C# might implement the coroutine functionality:



                    //Internal to Unity/C#

                    class Coroutine
                    Action<object> method;
                    object data;


                    Coroutine StartCoroutine(IEnumerator enumerator)
                    object data = CreateDataForEnumerator(method); //Very internal to C#
                    Action<object> method = GetMethodForEnumerator(enumerator); //Also very internal to C#
                    Coroutine coroutine = new Coroutine(method, data);
                    RunCoroutine(coroutine);
                    return coroutine;


                    //Called whenever this coroutine is scheduled to run
                    void RunCoroutine(Coroutine coroutine)
                    object yieldInstruction = coroutine.method(coroutine.data);
                    if (!data.shouldBreak)
                    //Put this coroutine into a collection of coroutines to run later, by calling RunCoroutine on it again
                    ScheduleForLater(yieldInstruction, coroutine);







                    share|improve this answer











                    $endgroup$



















                      3












                      $begingroup$

                      Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this:



                      class FireContinuouslyData 
                      int state;
                      bool shouldBreak;


                      object FireContinuously(FireContinuouslyData data)
                      switch (data.state)
                      case 0:
                      goto State_0;

                      while (true)
                      GameObject laser = ...;
                      laser.GetComponent...
                      //the next three lines handle the yield return
                      data.state = 0;
                      return new WaitForSeconds(fireTime);
                      State_0:




                      And internal to Unity/C# (since yield return is a native c# feature), when you call StartCoroutine, it creates a FireContinuouslyData object, and pass it in to the method. Based on the return value, it determines when to call it again later, simply storing the FireContinuouslyData object to pass it in next time.



                      If you ever did a yield break, it could internally just set data.shouldBreak = true and then Unity would simply throw away the data and not schedule it again.



                      And if there were any data that needed to be saved between executions, it would also be stored in the data for later.



                      An example of how Unity/C# might implement the coroutine functionality:



                      //Internal to Unity/C#

                      class Coroutine
                      Action<object> method;
                      object data;


                      Coroutine StartCoroutine(IEnumerator enumerator)
                      object data = CreateDataForEnumerator(method); //Very internal to C#
                      Action<object> method = GetMethodForEnumerator(enumerator); //Also very internal to C#
                      Coroutine coroutine = new Coroutine(method, data);
                      RunCoroutine(coroutine);
                      return coroutine;


                      //Called whenever this coroutine is scheduled to run
                      void RunCoroutine(Coroutine coroutine)
                      object yieldInstruction = coroutine.method(coroutine.data);
                      if (!data.shouldBreak)
                      //Put this coroutine into a collection of coroutines to run later, by calling RunCoroutine on it again
                      ScheduleForLater(yieldInstruction, coroutine);







                      share|improve this answer











                      $endgroup$

















                        3












                        3








                        3





                        $begingroup$

                        Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this:



                        class FireContinuouslyData 
                        int state;
                        bool shouldBreak;


                        object FireContinuously(FireContinuouslyData data)
                        switch (data.state)
                        case 0:
                        goto State_0;

                        while (true)
                        GameObject laser = ...;
                        laser.GetComponent...
                        //the next three lines handle the yield return
                        data.state = 0;
                        return new WaitForSeconds(fireTime);
                        State_0:




                        And internal to Unity/C# (since yield return is a native c# feature), when you call StartCoroutine, it creates a FireContinuouslyData object, and pass it in to the method. Based on the return value, it determines when to call it again later, simply storing the FireContinuouslyData object to pass it in next time.



                        If you ever did a yield break, it could internally just set data.shouldBreak = true and then Unity would simply throw away the data and not schedule it again.



                        And if there were any data that needed to be saved between executions, it would also be stored in the data for later.



                        An example of how Unity/C# might implement the coroutine functionality:



                        //Internal to Unity/C#

                        class Coroutine
                        Action<object> method;
                        object data;


                        Coroutine StartCoroutine(IEnumerator enumerator)
                        object data = CreateDataForEnumerator(method); //Very internal to C#
                        Action<object> method = GetMethodForEnumerator(enumerator); //Also very internal to C#
                        Coroutine coroutine = new Coroutine(method, data);
                        RunCoroutine(coroutine);
                        return coroutine;


                        //Called whenever this coroutine is scheduled to run
                        void RunCoroutine(Coroutine coroutine)
                        object yieldInstruction = coroutine.method(coroutine.data);
                        if (!data.shouldBreak)
                        //Put this coroutine into a collection of coroutines to run later, by calling RunCoroutine on it again
                        ScheduleForLater(yieldInstruction, coroutine);







                        share|improve this answer











                        $endgroup$



                        Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this:



                        class FireContinuouslyData 
                        int state;
                        bool shouldBreak;


                        object FireContinuously(FireContinuouslyData data)
                        switch (data.state)
                        case 0:
                        goto State_0;

                        while (true)
                        GameObject laser = ...;
                        laser.GetComponent...
                        //the next three lines handle the yield return
                        data.state = 0;
                        return new WaitForSeconds(fireTime);
                        State_0:




                        And internal to Unity/C# (since yield return is a native c# feature), when you call StartCoroutine, it creates a FireContinuouslyData object, and pass it in to the method. Based on the return value, it determines when to call it again later, simply storing the FireContinuouslyData object to pass it in next time.



                        If you ever did a yield break, it could internally just set data.shouldBreak = true and then Unity would simply throw away the data and not schedule it again.



                        And if there were any data that needed to be saved between executions, it would also be stored in the data for later.



                        An example of how Unity/C# might implement the coroutine functionality:



                        //Internal to Unity/C#

                        class Coroutine
                        Action<object> method;
                        object data;


                        Coroutine StartCoroutine(IEnumerator enumerator)
                        object data = CreateDataForEnumerator(method); //Very internal to C#
                        Action<object> method = GetMethodForEnumerator(enumerator); //Also very internal to C#
                        Coroutine coroutine = new Coroutine(method, data);
                        RunCoroutine(coroutine);
                        return coroutine;


                        //Called whenever this coroutine is scheduled to run
                        void RunCoroutine(Coroutine coroutine)
                        object yieldInstruction = coroutine.method(coroutine.data);
                        if (!data.shouldBreak)
                        //Put this coroutine into a collection of coroutines to run later, by calling RunCoroutine on it again
                        ScheduleForLater(yieldInstruction, coroutine);








                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 7 hours ago

























                        answered 8 hours ago









                        Ed MartyEd Marty

                        3,8781 gold badge7 silver badges12 bronze badges




                        3,8781 gold badge7 silver badges12 bronze badges
























                            1












                            $begingroup$

                            Another answer mentions that you are stopping co-routines when "Fire1" is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of "Fire1".



                            In your case however this code will not become 'stuck' in an infinite loop, which is what it looks like you're looking for an answer to - i.e. the while(true) loop, even if you did not stop it externally.



                            It won't get stuck but your coroutine won't end (without calling StopCoroutine() or StopAllCoroutines()) either. This is because Unity coroutines yield control to their caller. yielding is different to returning:



                            • a return statement will cease execution of a function, even if there is more code following it

                            • a yield statement will pause the function, starting at the next line after yield when resumed.

                            Usually, coroutines will be resumed each frame but you're also returning a WaitForSeconds object.



                            The line yield return new WaitForSeconds(fireTime) roughly translates as "now suspend me, and don't come back until fireTime seconds have passed".



                            IEnumerator FireContinuously()

                            // When started, this coroutine enters the below while loop...
                            while(true)

                            // It does some things... (Infinite coroutine code goes here)

                            // Then it yields control back to it's caller and pauses...
                            yield return new WaitForSeconds(fireTime);
                            // The next time it is called , it resumes here...
                            // It finds the end of a loop, so will re-evaluate the loop condition...
                            // Which passes, so control is returned to the top of the loop.




                            Unless stopped, this is a coroutine which, once started, will perform the whole loop once every fireTime seconds.






                            share|improve this answer









                            $endgroup$



















                              1












                              $begingroup$

                              Another answer mentions that you are stopping co-routines when "Fire1" is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of "Fire1".



                              In your case however this code will not become 'stuck' in an infinite loop, which is what it looks like you're looking for an answer to - i.e. the while(true) loop, even if you did not stop it externally.



                              It won't get stuck but your coroutine won't end (without calling StopCoroutine() or StopAllCoroutines()) either. This is because Unity coroutines yield control to their caller. yielding is different to returning:



                              • a return statement will cease execution of a function, even if there is more code following it

                              • a yield statement will pause the function, starting at the next line after yield when resumed.

                              Usually, coroutines will be resumed each frame but you're also returning a WaitForSeconds object.



                              The line yield return new WaitForSeconds(fireTime) roughly translates as "now suspend me, and don't come back until fireTime seconds have passed".



                              IEnumerator FireContinuously()

                              // When started, this coroutine enters the below while loop...
                              while(true)

                              // It does some things... (Infinite coroutine code goes here)

                              // Then it yields control back to it's caller and pauses...
                              yield return new WaitForSeconds(fireTime);
                              // The next time it is called , it resumes here...
                              // It finds the end of a loop, so will re-evaluate the loop condition...
                              // Which passes, so control is returned to the top of the loop.




                              Unless stopped, this is a coroutine which, once started, will perform the whole loop once every fireTime seconds.






                              share|improve this answer









                              $endgroup$

















                                1












                                1








                                1





                                $begingroup$

                                Another answer mentions that you are stopping co-routines when "Fire1" is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of "Fire1".



                                In your case however this code will not become 'stuck' in an infinite loop, which is what it looks like you're looking for an answer to - i.e. the while(true) loop, even if you did not stop it externally.



                                It won't get stuck but your coroutine won't end (without calling StopCoroutine() or StopAllCoroutines()) either. This is because Unity coroutines yield control to their caller. yielding is different to returning:



                                • a return statement will cease execution of a function, even if there is more code following it

                                • a yield statement will pause the function, starting at the next line after yield when resumed.

                                Usually, coroutines will be resumed each frame but you're also returning a WaitForSeconds object.



                                The line yield return new WaitForSeconds(fireTime) roughly translates as "now suspend me, and don't come back until fireTime seconds have passed".



                                IEnumerator FireContinuously()

                                // When started, this coroutine enters the below while loop...
                                while(true)

                                // It does some things... (Infinite coroutine code goes here)

                                // Then it yields control back to it's caller and pauses...
                                yield return new WaitForSeconds(fireTime);
                                // The next time it is called , it resumes here...
                                // It finds the end of a loop, so will re-evaluate the loop condition...
                                // Which passes, so control is returned to the top of the loop.




                                Unless stopped, this is a coroutine which, once started, will perform the whole loop once every fireTime seconds.






                                share|improve this answer









                                $endgroup$



                                Another answer mentions that you are stopping co-routines when "Fire1" is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of "Fire1".



                                In your case however this code will not become 'stuck' in an infinite loop, which is what it looks like you're looking for an answer to - i.e. the while(true) loop, even if you did not stop it externally.



                                It won't get stuck but your coroutine won't end (without calling StopCoroutine() or StopAllCoroutines()) either. This is because Unity coroutines yield control to their caller. yielding is different to returning:



                                • a return statement will cease execution of a function, even if there is more code following it

                                • a yield statement will pause the function, starting at the next line after yield when resumed.

                                Usually, coroutines will be resumed each frame but you're also returning a WaitForSeconds object.



                                The line yield return new WaitForSeconds(fireTime) roughly translates as "now suspend me, and don't come back until fireTime seconds have passed".



                                IEnumerator FireContinuously()

                                // When started, this coroutine enters the below while loop...
                                while(true)

                                // It does some things... (Infinite coroutine code goes here)

                                // Then it yields control back to it's caller and pauses...
                                yield return new WaitForSeconds(fireTime);
                                // The next time it is called , it resumes here...
                                // It finds the end of a loop, so will re-evaluate the loop condition...
                                // Which passes, so control is returned to the top of the loop.




                                Unless stopped, this is a coroutine which, once started, will perform the whole loop once every fireTime seconds.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered 8 hours ago









                                JoeJoe

                                1807 bronze badges




                                1807 bronze badges
























                                    1












                                    $begingroup$

                                    A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you yield return) using the IEnumerator that your function returns.



                                    Since you use the yield keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work?



                                    It is lazy and doesn't generate all the collection at once (and the collection may be infinite and impossible to be generated at once). Elements of the collection are generated as needed. Your function returns an iterator for Unity to work with. It calls its MoveNext method to generate a new element and Current property to access it.



                                    So your loop isn't endless, it runs some code, returns an element and returns control back to Unity so it's not stuck and can do other work such as handling your input to stop the coroutine.






                                    share|improve this answer









                                    $endgroup$



















                                      1












                                      $begingroup$

                                      A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you yield return) using the IEnumerator that your function returns.



                                      Since you use the yield keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work?



                                      It is lazy and doesn't generate all the collection at once (and the collection may be infinite and impossible to be generated at once). Elements of the collection are generated as needed. Your function returns an iterator for Unity to work with. It calls its MoveNext method to generate a new element and Current property to access it.



                                      So your loop isn't endless, it runs some code, returns an element and returns control back to Unity so it's not stuck and can do other work such as handling your input to stop the coroutine.






                                      share|improve this answer









                                      $endgroup$

















                                        1












                                        1








                                        1





                                        $begingroup$

                                        A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you yield return) using the IEnumerator that your function returns.



                                        Since you use the yield keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work?



                                        It is lazy and doesn't generate all the collection at once (and the collection may be infinite and impossible to be generated at once). Elements of the collection are generated as needed. Your function returns an iterator for Unity to work with. It calls its MoveNext method to generate a new element and Current property to access it.



                                        So your loop isn't endless, it runs some code, returns an element and returns control back to Unity so it's not stuck and can do other work such as handling your input to stop the coroutine.






                                        share|improve this answer









                                        $endgroup$



                                        A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you yield return) using the IEnumerator that your function returns.



                                        Since you use the yield keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work?



                                        It is lazy and doesn't generate all the collection at once (and the collection may be infinite and impossible to be generated at once). Elements of the collection are generated as needed. Your function returns an iterator for Unity to work with. It calls its MoveNext method to generate a new element and Current property to access it.



                                        So your loop isn't endless, it runs some code, returns an element and returns control back to Unity so it's not stuck and can do other work such as handling your input to stop the coroutine.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered 5 hours ago









                                        trollingchartrollingchar

                                        5341 gold badge1 silver badge11 bronze badges




                                        5341 gold badge1 silver badge11 bronze badges
























                                            1












                                            $begingroup$

                                            The reason is the keyword yield which has a specific meaning in C#.



                                            On encountering the words yield return a function in C# returns, as one would expect.




                                            Using yield to define an iterator removes the need for an explicit extra class



                                            [...]



                                            When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.




                                            So there is no infinite loop. There is a function/iterator that can be called an infinite number of times.



                                            The Unity function StartCoroutine() makes the Unity framework call the function/iterator once per frame.



                                            The Unity function StopAllCoroutines makes the Unity framework stop calling the function/iterator.



                                            And returning WaitForSeconds(time) from the iterator makes the Unity framework suspend calling the function/iterator for time.






                                            share|improve this answer









                                            $endgroup$



















                                              1












                                              $begingroup$

                                              The reason is the keyword yield which has a specific meaning in C#.



                                              On encountering the words yield return a function in C# returns, as one would expect.




                                              Using yield to define an iterator removes the need for an explicit extra class



                                              [...]



                                              When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.




                                              So there is no infinite loop. There is a function/iterator that can be called an infinite number of times.



                                              The Unity function StartCoroutine() makes the Unity framework call the function/iterator once per frame.



                                              The Unity function StopAllCoroutines makes the Unity framework stop calling the function/iterator.



                                              And returning WaitForSeconds(time) from the iterator makes the Unity framework suspend calling the function/iterator for time.






                                              share|improve this answer









                                              $endgroup$

















                                                1












                                                1








                                                1





                                                $begingroup$

                                                The reason is the keyword yield which has a specific meaning in C#.



                                                On encountering the words yield return a function in C# returns, as one would expect.




                                                Using yield to define an iterator removes the need for an explicit extra class



                                                [...]



                                                When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.




                                                So there is no infinite loop. There is a function/iterator that can be called an infinite number of times.



                                                The Unity function StartCoroutine() makes the Unity framework call the function/iterator once per frame.



                                                The Unity function StopAllCoroutines makes the Unity framework stop calling the function/iterator.



                                                And returning WaitForSeconds(time) from the iterator makes the Unity framework suspend calling the function/iterator for time.






                                                share|improve this answer









                                                $endgroup$



                                                The reason is the keyword yield which has a specific meaning in C#.



                                                On encountering the words yield return a function in C# returns, as one would expect.




                                                Using yield to define an iterator removes the need for an explicit extra class



                                                [...]



                                                When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.




                                                So there is no infinite loop. There is a function/iterator that can be called an infinite number of times.



                                                The Unity function StartCoroutine() makes the Unity framework call the function/iterator once per frame.



                                                The Unity function StopAllCoroutines makes the Unity framework stop calling the function/iterator.



                                                And returning WaitForSeconds(time) from the iterator makes the Unity framework suspend calling the function/iterator for time.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered 1 hour ago









                                                PeterPeter

                                                9,1201 gold badge23 silver badges40 bronze badges




                                                9,1201 gold badge23 silver badges40 bronze badges























                                                    babybrain is a new contributor. Be nice, and check out our Code of Conduct.









                                                    draft saved

                                                    draft discarded


















                                                    babybrain is a new contributor. Be nice, and check out our Code of Conduct.












                                                    babybrain is a new contributor. Be nice, and check out our Code of Conduct.











                                                    babybrain is a new contributor. Be nice, and check out our Code of Conduct.














                                                    Thanks for contributing an answer to Game Development Stack Exchange!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    Use MathJax to format equations. MathJax reference.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgamedev.stackexchange.com%2fquestions%2f174390%2fwhy-am-i-not-getting-stuck-in-the-loop%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                                    François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480