Journal 12 — Practice Coroutines in Unity

Chris Nielsen
2 min readApr 28, 2021

--

I first mentioned coroutines in my Journal 07 article on creating enemies. Coroutines in Unity and C# can be used for creating actions that need a specific timing, a series of steps, a series of music or visual effects, or running something that would take longer than a single frame.

Coroutines consist of a call to an IEnumerator function using the StartCoroutine command.

Coroutines in this example are used for spawning enemies at a regular interval. We add the StartCoroutine command in the Start Method, and use the Instantiate command plus a period of time to wait per each spawn in the IEnumerator function.

Unity C# Coroutine command in void Start
Unity C# IEnumerator to control spawn rate

Without a coroutine, if you spawned enemies in the Update Method, this is what would happen:

Unity Playmode — spawn enemies in Update (whoops!!)

Here’s the result with a coroutine:

Unity Playmode — spawn enemies at regular 5-second interval

Here’s another variation of the same coroutine with a random waiting period for spawning: yield return new WaitForSeconds(Random.Range(2f,5f)); This makes the enemy spawning a little more unpredictable as the game gets fleshed out.

Unity Playmode — spawn enemies at random 2–5 seconds interval

I appreciate your time stopping by.

Thanks!

--

--

Chris Nielsen
Chris Nielsen

Written by Chris Nielsen

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.

No responses yet