How to use coroutines in unity c#?

Share on social media

In this article, we will see what are the coroutines are and How to use coroutines to unity them in different scenarios, Not only using I will also share some tips for using them rightly.

There are multiple ways of using coroutines in unity. i.e. Pausing the code execution, Waiting until some task gets completed, Executing multiple coroutines in a certain order, etc. So there are multiple ways of using coroutines in unity.

Table of content

  1. What are coroutines?
  2. How to use coroutines in unity c#?
  3. How to end or break the coroutines? (like we return in functions)
  4. Ways of using yielding coroutines?
  5. How to stop coroutines?
  6. What are chain coroutines OR how to make chaining coroutines?
  7. What are the monobehaviour methods that also be coroutine?

What are coroutines?

A coroutine is a function that allows pausing its execution and resuming from the same point after a condition is met. We can say, a coroutine is a special type of function used in unity to stop the execution until some certain condition is met and continues from where it had left off.

This is the main difference between C# functions and Coroutines functions other than the syntax. A typical function can return any type, whereas coroutines must return an IEnumerator, and we must use yield before return.

Coroutines can be used for two reasons: asynchronous code and code that needs to compute over several frames.

So basically, coroutines facilitate us to break work into multiple frames, you might have thought we can do this using the Update function. You are right, but we do not have any control over the Update function. Coroutine code can be executed on-demand or at a different frequency (e.g., every 5 seconds instead of every frame).

For Example:-

IEnumerator MyCoroutine()  
{  
  Debug.Log("Hello world");  
  yield return null;   
//yield must be used before any return  
}

Here, you can see the basic example of unity in the coroutines. yield is a special return type in unity and tells it to pause the execution of the code for a particular amount of time or frames. And in the above example yield return null mean that unity will pause the execution for one frame and if you write it twice so it will wait for two frames.

Hope you got the basic idea of coroutines and how it looks like. Now we will see what are real case scenarios where we can use coroutines.

How to use coroutines in unity c#?

Here are the examples of using the coroutines:-

To wait for one frame:

// do something
yield return null;  // wait until next frame
// do something

To wait for three frames:

// do something
yield return null;  // wait until three frames from now
yield return null;
yield return null;
// do something

To wait approximately half a second:

// do something
yield return new WaitForSeconds (0.5f); // wait for 0.5 seconds
// do something

Do something every single frame:

while (true)
{
    // do something
    yield return null;  // wait until the next frame
}

This will wait for every single frame until the loop condition is satisfied.

For instance, you can also make a timer with this.

using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour
{

    public float timerSeconds = 60;
    private float timer = 0;

    
    void OnEnable()
    {
        StartCoroutine(StartTimer());
    }

    void OnDisable()
    {
        StopAllCoroutines();
    }

    IEnumerator StartTimer()
    {
        var wait = new WaitForSeconds(1f); // Using it below to reduce the garbage
        while (timer < timerSeconds)
        {
            timer++;
            Debug.LogFormat("{0} Seconds", timer);
            yield return wait;  // wait for a frame, about 1 second from now
        }
        Debug.Log("Timer Completed");
    }
}

The result is shown below in the image.

How to use coroutines in unity
Ways of using Coroutines in unity C#

We saw how to make a simple second-based timer. You may have also noticed I also used StopAllCoroutines don’t worry I am gonna cover it below topics.

How to end or break the coroutines?

Often you design coroutines to naturally end when certain goals are met.

So we use yield break to return from IEnumerator Just as we use return keyword with functions.

For Example:-

IEnumerator ShowExplosions()
{
    ... show basic explosions
    if(player.xp < 100) 
       yield break;
    ... show fancy explosions
}

Ways of using yielding coroutines?

We can use yield in different ways:

yield return null – This will Resume execution after All Update functions have been called, on the next frame.

yield return new WaitForSeconds(X) – Resumes execution after (Approximately) X seconds.

yield return new WaitForEndOfFrame() – Resumes execution after all cameras and GUI were rendered.

yield return new WaitForFixedUpdate() – Resumes execution after all FixedUpdates have been called on all scripts.

yield return new WWW(url) – This will resume execution after the web resource at URL was downloaded or failed.

yield return StartCoroutine(coroutine) – This will suspend the execution until the other coroutine executes completely.

How to stop coroutines?

There are several ways of stopping coroutines:-

String-based

Example:

StopCoroutine(“MyCoroutineName”)

IEnumerator Based

Example:

Coroutine myCoroutine = StartCoroutine(StartTimer());
StopCoroutine(myCoroutine);

What are chain coroutines and how to make chaining coroutines?

Coroutines can yield inside themselves, and wait for other coroutines.

So, you can chain sequences – “one after the other”.

This is very easy and is a basic, core, technique in Unity.

It’s absolutely natural in games that certain things have to happen “in order”. Almost every “round” of a game starts with a certain series of events happening, over a space of time, in some order. Here’s how you might start a car race game:

IEnumerator BeginRace()
{
  yield return StartCoroutine(PrepareRace());
  yield return StartCoroutine(Countdown());
  yield return StartCoroutine(StartRace());
}

So in the above example, We created one coroutine “BeginRace()” and called three coroutines inside it via yield return. So this way “Countdown” coroutine will execute after the “PrepareRace” coroutine will end and the same applies to the “StartRace” Coroutine.

So this way you can use your functions sequentially, Most of the time we need this to run some interdependent functionalities.

What are the mono behavior methods that also be coroutine?

There are three MonoBehaviour methods that can be made coroutines.

  1. Start
  2. OnBecameVisible
  3. OnLevelWasLoaded

This can be used to create, for example, scripts that execute only when the object is visible to a camera.

using UnityEngine;
using System.Collections;

public class RotateObject : MonoBehaviour
{
    IEnumerator OnBecameVisible()
    {
        yield return null;
    }
    
    private IEnumerator Start()
    {
        yield return null;
    }

    IEnumerator OnBecameVisible()
    {
        yield return null;
    }
}

So this is how we can use coroutines in unity c#.

You can also check the unity official document on coroutines here. Check out more articles here.

Aakash Solanki
Aakash Solanki

I am a professional unity game developer. I have a passion for creating immersive gaming experiences. For me writing articles feels like giving back to the community we have learned from. My hobbies involve playing games and writing articles and sometimes I also create youtube videos.


Share on social media

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top