Coroutines with Unity
Objective: Use Coroutines to spawn enemies every 5 seconds.
At this point in our game, I have created enemies, but now I need them to continually spawn at regular intervals. To do so, I am going to use a coroutine. A coroutine is going to allow me to pause the code for a short time (5 seconds in this case) so the enemies spawn in intervals rather than continuously.
To accomplish this, I first created an empty object and named it Spawn_Manager.
Next, I created a C# script called SpawnManager and dragged it onto Spawn_Manager object.
Then I created the gameobject that I wanted to spawn, the enemy prefab.
I went back to Unity and selected my Spawn_Manager in the hierarchy and dragged my enemy prefab into the Spawn_Manager.
Next, I used an IEnumerator named SpawnRoutine with an infinite while loop to instantiate our enemy prefab every 5 seconds. Normally we would want to avoid infinite loops, but in this case our yield is going to allow a pause that keeps our game from crashing.
Now when I go back to Unity to test my game, enemies begin spawning every 5 seconds.
Looking more like a real game every day!
For more information on Coroutines in Unity: https://docs.unity3d.com/Manual/Coroutines.html https://learn.unity.com/tutorial/coroutines#