Coroutines With Unity!

Ernesto Rocha
2 min readJun 5, 2021

--

Coroutines in Unity, allow us to suspend execution, or better yet when we can stop and start.

A coroutine method in Unity requires an IEnumerator, which needs to contain a yield return type, being the most common one WaitForSeconds. This allows us to set an amount of time in seconds before continuing the function.

This can be awesome for instantiating or changing a specific game object in a timeline.

Another common use of coroutines is to create a repeated instance of a function and to do this we need a while loop. It repeats while it is true or false.

We can start our coroutines with StartCoroutine, followed by the name of our coroutine and the brackets to call the function in brackets.

Our SpawnRoutine coroutine consists of a while loop that checks the bool we created. This allows the loop to run continuously while the bool is false. I’m using this to set a random spawn position along the x-axis.

In the Start method, it is simply calling our coroutine to start.

We yield a new return time of 5 seconds, allowing an enemy to spawn every 5 seconds, each in a random position, and being stored in a container to save cluttering up our hierarchy.

--

--

No responses yet