Coroutines with Unity!

Renato Figueiredo
2 min readDec 1, 2023

Objective: Learn how Coroutines work in Unity.

What are Coroutines ? Well, they are methods, just like any others, but they have an unique functionality. They can suspend their execution by using the Yield keyword, allowing us to wait a few seconds, or even conditions are met, until their execution is returned.

So how does that work ? Well, when creating a method, Void or Type-based, we use the keyword IEnumerator instead.

IEnumerator WaitForNameRoutine()

This allows us now to use the special keywords to manipulate time within the method.

IEnumerator WaitForNameRoutine()
{
while (true)
{
Debug.Log("My name is Renato.");
yield return new WaitForSeconds(3f);
}
}

In the example above, we created an infinite loop, that will print on the Console the phrase “My name is Renato.”, every 3 seconds.
By using the Yield keyword, we are able to stop the execution until a condition is met, in this case, we are telling the program to wait for 3 seconds, until the loop is run again.

When to use a Coroutine ?

Well, there are multiple uses for it, imagine games that spawn enemies while you are in an area, or until there are a limit of enemies in the screen.
By using a Coroutine, we can run a method for spawning enemies, and stop every couple of seconds, or all together until we have our conditions met.
This also helps us to manipulate time in specific situations, such as a Coundown system, that every second updates the display in the screen. By using a Coroutine we can wait exactly a second in order to update our UI.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response