Day 7: Coroutines

Have you ever tried to delay a function or make it wait for another action to finish? You may have found this difficult to do inside Update or using a normal function.

But don’t worry, because that’s where Coroutines come in.

What is a Coroutine

A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame. In C#, a coroutine is declared like this:

The difference is that, with a Coroutine, Unity knows to continue the method where it left off. What follows yield keyword will specify how long Unity will wait before continuing.

When to use them

We can use them when we need to execute one or more instructions that must be spaced in time, in seconds, or in frames.
For example, managing the spawn of enemies in a scene.

My SpawnManager generate an enemy every 3 seconds

To use a Coroutine it is not enough to simply call it as with a normal function. You need a specific keyword that will allow you to launch it, and also one to be able to stop it.

when you use StartCoroutine you can write the name as a string or as a method with brackets. Instead, when you use StopCoroutine you must write the name as a string.

An example
the objective is to change the color to my game object, in this case, is a simple cube.
To do this, I wrote this coroutine in the script attached to my game object.

I need to start my coroutine in the Start function like this

This will be the result.


To improve a coroutine we can limit the `new WaitForSecond` command, avoiding that it is instantiated every time. We can cache the reference and call the variable created, this also allows us to better control the timing of our coroutines.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andrea Alicino

Andrea Alicino


Unity developer and C# programmer. Currently looking for games industry employment.