paint-brush
Mastering Unity's Coroutinesby@infinity
1,229 reads
1,229 reads

Mastering Unity's Coroutines

by Rishabh AgarwalAugust 21st, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this blog, we will learn in-depth about coroutines in Unity using C#. Coroutines are special kinds of functions whose execution can be paused and resumed at any point. They provide us with the mechanism to execute logic asynchronously, independent of the frame rate of the actual game.
featured image - Mastering Unity's Coroutines
Rishabh Agarwal HackerNoon profile picture


Coroutine is the next natural thing (after MonoBehavior’s Update method) that beginners learn when starting on their Game Development journey in Unity. They provide us with the mechanism to execute logic asynchronously, which is independent of the frame rate of the actual game.


Coroutines can be used for several tasks that are commonly required in any game -


  • Executing logic that spans more than one frame
  • Spawning game objects periodically
  • Moving a game object from one position to another across several frames


In this blog, we will learn in-depth about coroutines in Unity using C#.


What are Coroutines?

Coroutines are a general programming paradigm. They’re not specific to Unity to C#


The word “coroutine” is composed of two words: “co” (cooperative) and “routines” (functions). Coroutines are special kinds of functions whose execution can be paused and resumed at any point. They are different from standard functions that usually run to completion before returning.


Coroutines can be considered lightweight threads that do not block a thread when waiting on another coroutine.



Source: https://www.educative.io/answers/what-is-a-coroutine



Coroutines in Unity

Consider the task of changing a game object’s state every minute. This game object can be a clock whose state we want to update based on time and not on every frame. We can not have this logic inside the update method since that is called every frame.


This is where a coroutine comes to the rescue.


IEnumerator tickClock() {
  while(true) {
    yield return new WaitForSeconds(60);
    this.addMinute();
  }
}


The yield keyword is used to indicate that the coroutine is voluntarily returning control to its caller. An extra object can be returned to the caller along with the yield. This returned object indicates to the caller exactly when to call the coroutine again.


In our scenario, we tell the caller that this coroutine should be invoked 60 seconds after we hit the yield statement. Because the yield statement is included within a while loop, the code flow ensures that this coroutine is invoked every 60 seconds.

Starting a coroutine

Once we have written the coroutine, we should start it. Unity provides MonoBehaviour.StartCoroutine method to start a coroutine. So we can simply start our tickClock subroutine from the Start method.


void Start() {
  StartCoroutine(tickClock);
}


With this, our Coroutine is now started and is handled by Unity.


Yielding for a single frame

We can use an object of the class WaitForSeconds to pause a coroutine for a certain duration. We can also pause a coroutine for a single frame. To do so we simply return a null object. Here is how you would do that.


IEnumerator tickEveryFrame() {
  while(true) {
    yield return null;
    Debug.Log("Ticking");  
  }
}


Stopping a coroutine

Just like the StartCoroutine method, we have the StopCoroutine method. This can be used to stop a coroutine.

Things to keep in mind while using coroutines

Following are some things to keep in mind when working with coroutines -

  • Coroutines can lead to memory leaks if left unnoticed.
  • Once the yield statement is executed the next call to the coroutine will only be made in the next frame.
  • Coroutine is attached to the game object and if the game object is destroyed, the coroutine is also destroyed.

The use of coroutines in Unity opens up new ways to implement interesting features in our game. If used properly, they can be a real asset to developers.


If you enjoy reading such articles on programming and software do follow for more.