Unity: Coroutines

Timo Schmid
2 min readApr 13, 2021

You have the following objective:

At the very first, we need to create a GameObject which will be spawned.

A coroutine has always the return type IEnumerator.

Because this coroutine should run as long as our application is running, we need a while() loop.

BEWARE!: Be cautious when you use a while(true) loop! Because it is an endless loop, it can cause your Unity Editor to get stuck and eats more and more of your system resources. You can just get out of this by killing the Unity task in the Task Manager. Therefore, any unsaved work will be lost!

In this while(true) loop, we tell Unity what it should instantiate and where it should do that.

Because we want that to happen at every second, we need to automatically repeat this method every second. For this, we can use yield return new WaitForSeconds().

After the entered time has passed and if the conditions do still apply, Unity will repeat the Instantiation.

The required Coroutine

Now that we have the Coroutine set up in our code, we need to start and call the Coroutine. This works a bit different as calling a normal method.
For calling a Coroutine, we need to use StartCoroutine(<CoroutineName>);

We just want to start the Coroutine once. Therefore, we will call the StartCoroutine() method in void Start().

Don’t forget to call the Coroutine!

A working coroutine for this task should look like this:

Working end result!

--

--

Timo Schmid

The mission? Becoming a game developer! RPG is the dream! Writing down my journey here for me and for everyone interested. Thanks for showing interest :)