Day 13: Coroutines — How to Time Events Perfectly

There’s a lot of events in video games that are supposed to happen at precise times. Cut scenes need to keep the camera in certain place for some time, before switching to a different place. During the gameplay, certain things might happen every few seconds that put on obstacle in the player’s way.

Coroutines are a very useful took that we can use to keep precise track of when certain events are supposed to happen, and execute those events right when they should.

Let’s continue the space shooter game from last time. The goal is to introduce a Spawn Manager that will create a new enemy every 5 seconds.

First we need to actually create that Spawn Manager object in Unity. Here, we use an Empty game object, which is something “invisible” in the game world and can only affect things with an attached script.

Now lets open up the SpawnManager script and add some variables. We need to keep track of how often enemies should spawn, as well as the enemy GameObject that we actually want to instantiate every time.

Here’s where a coroutine is useful. We can set up a loop that creates a new enemy every 5 seconds. We create one by using the IEnumerator return type.

Now we get the coroutine running in the Start method.

Enemy.RandomPositionAtTop is a new static helper method in the enemy class. We can call this method in any code, even ones that don’t have access to enemies.

Now we can play the game, and we can see more red enemy squares appear over time:

We can also see more enemies appearing in the hierarchy. While it’s nice that this confirms that the spawn manager is working, we don’t actually want all these copies of enemies showing up in the hierarchy like this since it’s messy and takes up space for other things we may want to look at. Next time, we’ll see how we can clean this up a bit.



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
Blake Zoeckler

Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.