How to use Coroutines in Unity
Create a coroutine to spawn an enemy every X seconds
A Coroutine is a function that can pause and wait while the rest of the code continues to run. Then after the wait it can continue the coroutine right where it waited.
IEnumerator type function is used to create an Coroutine in Unity. This allows us to use ‘yield’ which is used to tell Unity to wait. You always need to have a yield within IEnumerator.
Code Example — Coroutine
We want our script to spawn an enemy every 3 seconds.
To start the coroutine use StartCoroutine and state the name just like evry other function.
//wait for 3 seconds in float
yield return new WaitForSeconds(3f);
The yield part is what makes the IEnumerator function different. In our example it will wait for 3 seconds then continue to run the code from there again. For us it means it return to the top of the while loop again.