Coroutines

Karissa Huynh
2 min readDec 18, 2020

--

In music, a band must keep track of the rhythm to know when to enter and play on beat. This is the similar to the Coroutines we use in Unity. Coroutines allows is to create sequence events that allow us to yield events. Like creating Choreograph in our game.

Specifically we used the coroutine IEnumerator.. a function that has the ability to pause execution & return control to unity but then continue where it left off on the following frame.

SO why do we use IEnumerator? In other words, instead of using void in our method. The IEnumerator allows us to use the line ‘yield’. Which tells unity, to wait X-amount of seconds before executing the next. Specifically, how we create our dance routine in our games!

To create our coroutine we need the following

  • Coroutine type IEnumerator
  • while loop
  • figure out how to start Coroutine.

Note: We want to continuously use our coroutine to spawn enemies so the while loop with be indefinite(later will change). The while loop usually will crash since it taking up space since it is ran infinitely, but worry not.. we will use yield to allow our machine to breathe and not crash.

In the while loop we want it to instantiate our enemy game object and use our yield for 5 secs before spawning a new enemy.

So how do we Spawn enemy prefabs?

We Spawn enemies by first creating a Serialized field variable. Then, go into Unity and drag our Enemy Prefab inside the SpawnManager Script looking for an Enemy prefab. Now our script has a reference to the enemy prefab!

We start our our coroutine in the start method by using StartCoroutine().

And viola! We have used coroutines to timely choreograph our enemy game objects!

--

--

No responses yet