Makes it Keep Running with Coroutine- Game Dev Series 11

S.J. Jason Liu
3 min readMay 6, 2021

Look what have I built? A enemy-spawning machine!

Previous: Contact to Other Scripts with GetComponent

Now we need to make more enemies since there is still only one in our game. To create a enemy with regular time, we will need a coroutine.
The most common use in coroutine is creating a loop for codes. Inside this loop, the function can work constantly until we break the loop.

First, we need a game object to do the loop for spawning. Let’s create an empty with right click and name it Spawn_Manager. Notice there is a underscore between words.

Then we create a script called SpawnManager, attach it to the game object and open it.

To run a function with coroutine, we need to use IEnumerator.
Create a function called SpawnRoutine() with IEnumerator.

Before we make the coroutine works, we need to create a variable to storage the enemy prefabs.

Then we can create the routine function.

To create a loop, we will use while() loop. A while loop is when the condition inside the parentheses is met, the code would repeat. In this situation, we need a while loop to make our enemy keep spawning during the whole game.

We use “true” inside the parentheses which means always do the loop. Notice that if you use an infinite loop, it might cause some lag to your system.

Let’s finish the code to spawn our enemies.

With a coroutine, you would need the last line of code:

yield return new WaitForSeconds(5);

A coroutine will always use yield. Yield means taking a break and do the rest of this line. In this line, we want this coroutine to start over after 5 seconds.

Then we need another method to start this coroutine.

Use StartCoroutine() to start the routine function. Then our enemy spawning should work. Before we check our result, we can cleanup our code.

Let’s create a Vector3 variable to keep the position in Instantiate() less messy.

Now we can check the result.

--

--

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.