Normally when a method is called, it is executed line by line and there is no way to delay it. Thanks to a coroutine, we can pause the execution for a specific amount of time, or wait until some condition is met.

A simple example using coroutine to spawn enemies:

There is an error in our method. the “yield return” statement must be included somewhere in your method. We will fix it in a moment.

Next, we need a position for our enemy to spawn on. Then, we instantiating our enemy. I talk about “Random.Range()” and “Instantiate()” in previous articles.

Random.Range(-9f, 9f) — Get a number between -9 and 9.
Instantiate(GameObject we want to spawn, position, rotation).

Now, we want our enemies to spawn every 5 seconds:

Thanks to this line of code execution of our code will be stopped for 5 seconds.

The last thing we need to do is to put everything in a while loop:

Now, our method will not stop spawning our enemies until we change “_stopSpawning” variable.

To call our coroutine we need to use “StartCoroutine”: