‘Coroutines with Unity!’
On this article we are going to learn the basics of coroutines.
Unity's IPA description of coroutines is: MonoBehaviour.StartCoroutine returns a Coroutine. Instances of this class are only used to reference these coroutines, and do not hold any exposed properties or functions.
A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes.
On our Space Shooter game, we will use the StartCoruotine function to spawn the enemy prefab every 5 seconds.
First of all, we need to create an empty object and we will call it Spawn_Manager.
Now that we have a Spawn_Manager we need to create a SpawnManager Script and attach it to our Spawn_Manager object.
At this point, on the Spaw manager Script, we need to create a private GameObject funcion that we are going to call it _Enemy Prefab, and also, we need to create an IEnumerator class. On this class we need to create a while loop that it will allow us to spawn the Enemy prefab every 5 seconds.
The last step that we need to do for the coroutine to run properly in our game is to call the Start Coroutine function in the void start method.
Now, when we run the game, the Enemy prefab will spawn every 5 seconds.