Project 1: Space Shooter

Introduction to Unity Coroutines

And how to make a simple spawn manager

Simple spawn manager in action.

Since I don’t know how many enemies the player wants to shoot, I have to figure out a way to spawn them as long as possible. To do that the simple way, Unity provides a method called Coroutine. This is a specialized script which can hand the execution back to where it was called, so that the program can continue, all the while waiting for some condition to return the execution back to the coroutine.

In my case this means that I want to spawn an enemy with Instantiate method on regular intervals, but in between those spawning times I want the other part of my program to have the control. That is, I want my player to be able to move and shoot between every spawning.

So after creating an empty object, I called it Spawn_Manager, and attached a SpawnManager script to it, I can start the implementation. First thing is to add a new IEnumerator type method to my SpawnManager script, I called it SpawnRoutine. For my coroutine to work, the method which starts the coroutine needs IEnumerator type as its input argument.

To run the code indefinitely, I put everything inside a -loop with an argument . In most cases this is a bad practice, because the loop will continue on forever, or at least as long as the computer running it has enough memory to handle whatever is inside the loop. But in this case, the coroutine will pause the loop at intervals that I set for it. And I set it to one second, so every second a new enemy is spawned, and once they exit the screen at the bottom they teleport back to the top in a random location along the x-axis.

Thus I have to instantiate my enemy inside the loop, and then do a with a value of a method called WaitForSeconds. This way the coroutine will pause the execution of the while-loop for one second and pass the execution back to the rest of the program.

Easiest way to use a coroutine to spawn enemies.

Then all I have to do is to start the coroutine. Best place for this is at the Start method of my script, so that the SpawnManager starts when the program starts. The code for starting the coroutine is quite easy, it’s just StartCoroutine where the argument passed for it is the coroutine method.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store