Coroutines in Unity
When it comes to spawning enemies in game, coroutines are life savers. Coroutines allow you to define a wait period before code executes.
To create a coroutine, you simply create an IEnumerator which require a yield, or delay. For example, creating coroutine to handle spawning enemies for a 2D space shooter game.
To start, create the IEnumerator and name it something relevant, like SpawnRoutine. Then since we want enemies to continuously spawn for the life of the game, we create a while loop with a bool condition so we can stop it if the player dies. Inside the while loop we create the enemy, the example below is with object pooling. Then it’s just setting the position of the enemy we create. Then we get the
This sets the delay before the script continues its execution. Yield return sets up the following as a wait period, and the new WaitForSeconds(Random.Range(1f, 5f)) sets the delay to be a random float value between the values of 1 and 5.
With the coroutine created, it is simply called with StartCoroutine() with the name of your coroutine:
Now one enemy will be created after a delay of 1–5 seconds and that completes the creation of coroutines.