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 -
In this blog, we will learn in-depth about coroutines in Unity using C#.
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.
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.
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.
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");
}
}
Just like the StartCoroutine method, we have the StopCoroutine method. This can be used to stop a coroutine.
Following are some things to keep in mind when working with coroutines -
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.