Spawning enemies: Coroutines
Objective: Periodically spawn enemies in the scene using an IEnumerator coroutine.
Unity executes functions in void Update to completion every frame. If SpawnEnemies() were called every update that would be too many enemies. How do I create a function that can track time and spawn enemies every 5 seconds instead of every frame? The answer is starting an IEnumerator coroutine in void Start which has a while loop and a yield return statement. An IEnumerator is a function, like Start and Update, except that the function can be interrupted using the yield return statement, allowing completion of other code, and returned to in the following frame. Looking at the function below, the coroutine is started in the void Start() function, so just once. If SpawnEnemies() were started in the void Update() then it would restart every frame and the the routine could never run to completion, not to mention too many enemies.
The function initiates an infinite while loop that will run as long as the game is running. The while loop is necessary to spawn enemies throughout the game, and the critical yield within the while loop prevents this infinite loop from crashing the program. A random number is used to Instantiate enemies along the top of the screen, note that the enemy prefab needs to be assigned in the inspector. The routine then yields for the remainder of the frame to allow completion of other code, but returns to the yield statement on the next frame. If the wait time has not passed the function yields until the wait time has passed, at which time the function continues the script, restarting the while loop, spawning another enemy, and yielding once more. Below is shown the spawning of yellow enemies, using the above script, which eventually destroy the blue player.