Coroutines in Unity cover image

Coroutines in Unity

A coroutine is like a function that can be executed with the ability to pause the execution function and resume the execution after some time when required.

A coroutine is generally used in two cases:

1. When we want to delay or pause the execution of some scripts

2. When we want to run timed events like health bar regeneration after every 3 (or n) seconds

Usage

Declaring a coroutine:

IEnumerator CreateExplosion() {
    //make explosion effect
    yield return new waitforseconds(1); //this statement will pause the execution for 1 second
    //make smoke effect
    yield return new waitforseconds(1);
    //destroy explosion and smoke
}

As you can see, a coroutine has IEnumerator as its return type.

With IEnumerator as it’s return type, it must use the yield operator to yield values (time delay in our case).

The coroutine CreateExplosion have no input parameters. The input parameters can be defined by the user. It may or may not have input parameters depending on the requirements.

With some input parameters, its declaration might look like:

IEnumerator CreateExplosion( Vector3 position ) {

....

Calling a Coroutine

We just created a coroutine named CreateExplosion. To call the coroutine, we use the StartCoroutine method.

The code to execute the CreateExplosion coroutine would look like:

StartCoroutine(CreateExplosion());

Canceling the Coroutine’s Execution

There are certain cases, we need to stop the coroutine’s execution in between & this is quite easy and can be done in any of the two ways:

Option 1: Canceling a coroutine using Coroutine name

In the case above, the name of the coroutine is CreateExplosion and this name can be used to stop the execution of the coroutine. To stop a coroutine, we use the StopCoroutine method with the coroutine name passed to it as its parameter.

StopCoroutine("CreateExplosion");

Option 2: Canceling a coroutine using its reference

The StartCoroutine method to execute a coroutine has a return type of Coroutine. We can store the reference of an executing coroutine and use it to cancel it at any time.

Coroutine explosionCoroutine = StartCoroutine(CreateExplosion());

The code above will execute the coroutine. To stop the executing Coroutine, we use the code:

StopCoroutine(explosionCoroutine);

Update vs Coroutine

The major difference between Update and Coroutine is that an Update runs every frame & its lifecycle cannot be controlled whereas we can control the lifecycle of a coroutine. By controlling the lifecycle, I mean controlling the execution, stopping the executing on demand & even pausing the executing using the yield operator.

Which one to use?

While we can write all of our update logic in a coroutine, but we shouldn’t. A coroutine execution is much heavier compared to an Update logic under similar use cases like infinite execution or execution on every frame.

We should only use coroutine when the execution is much smaller (like a health bar would regenerate after every 5 seconds) compared to Update. We can also use a coroutine when there is a limited number of executions of the logic like:

void Update(){
if(!delete)
return;

Destroy(transform);
}

In the code above, it will keep running the if check until the boolean should be triggered. Instead, we can use a coroutine here to destroy the gameobject with some animations being applied to it. This will reduce the overhead for every frame to check if the gameobject should be destroyed or not.

 


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.