Wait Just a Second: Coroutines with Unity

Ryan McCoach
2 min readApr 2, 2021

Computers can execute programs at blazing speeds, but there are times when you just need it to slow it down and take a breath. How can you do this? Coroutines. Coroutines allow you to return WaitForSeconds, which pause the script for the set amount of time before continuing on.

A Coroutine was used to Instantiate a new ball every 2.5 seconds.

In creating a Coroutine, we will be using an IEnumerator method and give it an appropriate name. In picture above, an IEnumerator called SpawnRoutine was created to control when a new ball will be spawned or created. In While Loop, a returned a new WaitForSeconds, which will have the script wait 2 1/2 seconds before moving on to the part of the script that creates and position the new ball. It is crucial when using a While Loop, you use a WaitForSeconds, to give your program a chance to breath. If you do not, you will most likely crash the program.

Once the Coroutine is created, you just to call it so it can be used.

--

--