Unity - Coroutines


Coroutines are the most helpful tools when making games in Unity. Let us consider the line of code shown below to understand what coroutines is all about.

IEnumerator MyCoroutineMethod() {
   // Your code here…
   yield return null;

Generally, if you call a function in Unity (or C#, really), the function will run from start to finish. This is what you would consider “normal” behaviour as far as your code is concerned. However, sometimes we want to deliberately slow down a function or make it wait for longer than the split second duration that it runs. A coroutine is capable of exactly that: a coroutine is a function that is capable of waiting and timing its process, as well as pausing it entirely.

Let us consider an example to understand how a coroutine works. Say we want to make a square that changes its color between red and blue in 1-second intervals.

To begin with, we create a sprite. Next, create a new script, and name it ColorChanger. In this script, we get a reference to the Sprite Renderer of the sprite. However, we will use a different way of getting the component. Instead of dragging and dropping the component into a slot like we have done so far, we will ask the code to detect the component itself.

This is done through the GetComponent method, which returns the first matching component it detects. Since we only use one Sprite Renderer per object, we can use this method to automatically detect and get a reference to our renderer each time.

Remember that the renderer is responsible for making the sprite actually visible on-screen. The renderer has a color property that affects the global color of the sprite; this is the value that is to be modified. Making the Color values public will let us pick them through the editor in your operating system’s default color picking program.

private SpriteRenderer sr;

public Color color1;
public Color color2;

void Start () {
   sr = GetComponent<SpriteRenderer>();

IEnumerator ChangeColor() {
   while (true) {
      if (sr.color == color1)
         sr.color = color2;
         sr.color = color1;
      yield return new WaitForSeconds(3);

Now, we will trap our coroutine function in a while loop.

To create a coroutine in C#, we simply create a method that returns IEnumerator. It also needs a yield return statement. The yield return statement is special; it is what actually tells Unity to pause the script and continue on the next frame.

There are a number of ways that can be used to yield return; one of which is to create an instance of the WaitForSeconds class. This makes the coroutine wait for a certain amount of real-world seconds before continuing.

Let us compile our code and head on back to Unity. We will simply pick our alternating colors, and hit play. Our object should now switch between the two colors in 3 second intervals. You can make the interval a public variable and adjust the frequency of the color changes as well.

Coroutines are extensively used for timed methods, like the one we just did. The variety of WaitForX methods have their own uses. Coroutines are also used to run “on the side” processes that run on their own while the game runs simultaneously. This is useful, for example, to load off-screen parts of a large level while the player starts at one point.