Coroutines with Unity!

A lot of our game logic uses the update function and this works very well for the movement of the ship or to fire the laser. The same logic couldn't be applied to making enemies spawn over time, like it wouldn't make sense to spawn our own enemies by the press of a button.

For this logic we can use a coroutine to execute this game logic over time. A coroutine could also be used for a power up or to delay an event.

We call a coroutine by using IEnumerator. I will use this to spawn an enemy in the game every 5 seconds.

this will spawn an enemy along the x at a random position. the line “yield return new” is necessary to allow the command to breath and can be used again and again to give a command.

To start the coroutine we can call it within void start “StartCoroutine(SpawnRoutine());”

Enemies Spawning

--

--

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