Coroutines

Scripting a checklist for your objects

Simon Truong
2 min readMay 9, 2021

--

A coroutine is a function that is gives an object a set amount of actions to complete set within a schedule like manner. An example would be setting up an spawn manager and having enemies spawn after a set amount of time.

How to apply coroutines

There are many ways to apply coroutines into your scripts and can be used effectively due to its optimization. Making a spawn manager for spawning enemies, we would need an type of coroutine called “IEnumerator”. With “IEnumerator”, it allows the coroutine to “yield” its function and “wait” a set amount of seconds before restarting the coroutine.

An Spawn Routine with an 5 second wait.

In this example, we have placed everything within a “While Loop” since we want to have the enemies infinity spawn, but be cautious since while loops are infinite and take up quiet a bit of compute memory. If not handle properly, it will cause the program to crash.

In the while loop, we will instantiate the enemy prefabs at random values on the scene. The “Yield return” function allows us to pause the coroutine to a set specification. In this example, we use “Wait for Seconds” therefore after a set amount of seconds has passed, the coroutine would pick up function again.

How to Start a Coroutine

There are two ways to start an coroutine, either through a string or through and optimized way by invoking the method name itself.In the void start section type in “StartCoroutine(**name given to the IEnumerator**)”.

Starting a Coroutine

--

--

Simon Truong

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.