Jump to content
  • Advertisement
Sign in to follow this  
boxofnuggets

Unity Unity 2D StartCoroutine

This topic is 1423 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello,

 

Fairly recently, me and a good friend of mine have decided to take on a small project in Unity 2D, a pixelated platformer called "Super Jetman 2D". He's making the sprites, and I'm in charge of scripting, and actually pulling it all together using Unity. However, I've been struggling when it comes to StartCoroutine. I've looked at the Scripting API and Manual, and still can't seem to wrap my head around it. I'm a beginning programmer (barely 8 months or so), so please keep it fairly light on terminology :)

 

Cheers,

boxnuggets

Share this post


Link to post
Share on other sites
Advertisement
Coroutines are functions that can 'yield'. 'Yield' is similar to 'return', except that it also remembers the point in the function that it returned from (and the variables it was using at that point), and can come back to it later.

In order to remember where to resume a coroutine, the compiler changes functions that have 'yield' in them into hidden classes which contain all of the variables and logic needed to do this.

http://csharpindepth.com/articles/chapter6/iteratorblockimplementation.aspx


Calling the coroutine function will create a new instance of the hidden class - the arguments you pass to the function are used to initialize that instance. After that, the instance has two members you use to interact with it: MoveNext (a function) which executes the coroutine until its next 'yield', and Current (a property) which gets the value of the last 'yield return x;' statement.

Unity's StartCoroutine function calls the function (creating one coroutine instance) and immediately calls MoveNext once. After that, the behavior of the coroutine depends on how you yield:

- "yield return null;" will tell Unity to resume the coroutine on the next frame.
- "yield return new WaitForSeconds(5);" will resume once 5 seconds have passed.
- "yield return www;" (where www is a WWW instance) will resume after the WWW object has finished its web request.
- "yield return StartCoroutine(...);" will start a nested coroutine and resume the current coroutine once the nested one completes.
- "yield break;" (or if execution reached the end of the function) stops the coroutine.


StartCoroutine stores the coroutine instance on the GameObject it was called on (or the GameObject associated with the component it was called on). The coroutine will only run while that GameObject is still active. If you deactivate or destroy the GameObject, all coroutines that were "hosted" by that GameObject will be stopped.

For a more detailed view of exactly when coroutines execute during Unity's execution process, refer to the flowchart at the bottom of this page:

http://docs.unity3d.com/Manual/ExecutionOrder.html

In particular, look for the nodes of the flowchart that start with "yield". Those points in the flowchart indicate where Unity may decide to call MoveNext, depending on which kind of yield was used the last time the coroutine ran. Edited by Nypyren

Share this post


Link to post
Share on other sites

Coroutines are like functions that can be paused. This lets you write game logic sequentially.
 

public IEnumerator DoStuff()
{
    float distance = 10.0f;
    while (distance > 0.0f)
    {
        float moveBy = speed * Time.deltaTime;

        transform.position += Vector.forward * moveBy;
        distance -= moveBy;

        // wait until the next frame
        yield return null;
    }

    // wait for one second
    return new WaitForSeconds(1.0f);

    FireWeapon();
}
// Then to run the coroutine
StartCoroutine(DoStuff());

// this line of code will be run before DoStuff finishes
// Unity automatically handles continuing the 
// coroutine each frame in the background
Foo();

Share this post


Link to post
Share on other sites

Coroutines are functions that can 'yield'. 'Yield' is similar to 'return', except that it also remembers the point in the function that it returned from (and the variables it was using at that point), and can come back to it later.

In order to remember where to resume a coroutine, the compiler changes functions that have 'yield' in them into hidden classes which contain all of the variables and logic needed to do this.

http://csharpindepth.com/articles/chapter6/iteratorblockimplementation.aspx


Calling the coroutine function will create a new instance of the hidden class - the arguments you pass to the function are used to initialize that instance. After that, the instance has two members you use to interact with it: MoveNext (a function) which executes the coroutine until its next 'yield', and Current (a property) which gets the value of the last 'yield return x;' statement.

Unity's StartCoroutine function calls the function (creating one coroutine instance) and immediately calls MoveNext once. After that, the behavior of the coroutine depends on how you yield:

- "yield return null;" will tell Unity to resume the coroutine on the next frame.
- "yield return new WaitForSeconds(5);" will resume once 5 seconds have passed.
- "yield return www;" (where www is a WWW instance) will resume after the WWW object has finished its web request.
- "yield return StartCoroutine(...);" will start a nested coroutine and resume the current coroutine once the nested one completes.
- "yield break;" (or if execution reached the end of the function) stops the coroutine.


StartCoroutine stores the coroutine instance on the GameObject it was called on (or the GameObject associated with the component it was called on). The coroutine will only run while that GameObject is still active. If you deactivate or destroy the GameObject, all coroutines that were "hosted" by that GameObject will be stopped.

For a more detailed view of exactly when coroutines execute during Unity's execution process, refer to the flowchart at the bottom of this page:

http://docs.unity3d.com/Manual/ExecutionOrder.html

In particular, look for the nodes of the flowchart that start with "yield". Those points in the flowchart indicate where Unity may decide to call MoveNext, depending on which kind of yield was used the last time the coroutine ran.

Thanks for the reply! This really helps me. So, basically, a coroutine is a function that can effectively pause, execute code in other classes/functions, then resume the flow of control in the function/class it's in.

One question though, what do you mean by "hidden classes"?

Share this post


Link to post
Share on other sites

 

Coroutines are like functions that can be paused. This lets you write game logic sequentially.
 

public IEnumerator DoStuff()
{
    float distance = 10.0f;
    while (distance > 0.0f)
    {
        float moveBy = speed * Time.deltaTime;

        transform.position += Vector.forward * moveBy;
        distance -= moveBy;

        // wait until the next frame
        yield return null;
    }

    // wait for one second
    return new WaitForSeconds(1.0f);

    FireWeapon();
}
// Then to run the coroutine
StartCoroutine(DoStuff());

// this line of code will be run before DoStuff finishes
// Unity automatically handles continuing the 
// coroutine each frame in the background
Foo();

Thanks for the reply! I appreciate the example included. So the coroutine is basically like a function, except it can choose when the it "yields" and continues the code in regular order.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!