Sign in to follow this  

Unity Unity 2D StartCoroutine

This topic is 1113 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
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

This topic is 1113 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628726
    • Total Posts
      2984410
  • Similar Content

    • By INTwindwolf
      THE PROJECT

      INT is a 3D Sci-fi RPG with a strong emphasis on story, role playing, and innovative RPG features such as randomized companions. The focus is on the journey through a war-torn world with fast-paced combat against hordes of enemies. The player must accomplish quests like a traditional RPG, complete objectives, and meet lively crew members who will aid in the player's survival. Throughout the game you can side and complete missions through criminal cartels, and the two major combatants, the UCE and ACP, of the Interstellar Civil War.
      Please note that all of our current positions are remote work. You will not be required to travel.
      Talent Needed
       
      Unity Engine Programmer
      Website Administrator
      3D Animator
      We have made great strides in the year 2017! INT has received a comprehensive face-lift compared to the start of the year. We look forward to a productive, fruitful year 2018!
      Revenue-Share
      This is the perfect opportunity to get into the game development industry. Being an Indie team we do not have the creative restrictions often imposed by publishers or other third parties. We are extremely conscientious of our work and continuously uphold a high level of quality throughout our project.
      We are unable to offer wages or per-item payments at this time. However revenue-sharing from crowd-funding is offered to team members who contribute 15-20 hours per week to company projects, as well as maintain constant communication and adhere to deadlines. Currently the crowd-funding campaign is scheduled for the year 2018. Your understanding is dearly appreciated.
       
      Thank you for your time! We look forward to hearing from you!
       
      John Shen
      HR Lead
      Starboard Games LLC
    • By Apollo Cabrera
      Energy particles being harnessed by collection multi-hedron energy matrix. Whuuuttt?
      Love it :)
    • By AndySv
        Total Music Collection (http://u3d.as/Pxo)   THE COLLECTION CONTAINS:   Mega Game Music Collection   Universal Music Collection   Huge library of high quality music for any project! All at an incredibly low price!   - 2,5GB of high quality audio - 100+ different music tracks - Loop and short versions   Action, fantasy, casual, horror, puzzle, epic, dramatic, romantic, positive, inspiring, motivational and more!
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064
  • Popular Now