Day 14: Coroutines with Unity!

Objective: Spawn enemies using a Coroutine.

To start of spawning enemies we will need to create an empty game object to attach the script to.

Now create the script.

In the Script we need a reference to the game object that will be spawning.

Now we will create a IEnumerator called SpawnRoutine().

This is where we will instantiate the enemy. We want the enemy to spawn above the screen and at random X positions. We need to create a Vector 3 and use random.range for the X position, input the y and z values as well.

Now this will only run once and after one frame. We want it to wait 5 seconds between each spawn.

Now to make it keep spawning while the player is alive. We need to create a bool to know when to stop spawning.

Now we need to use it. We will use a while loop in the IEnumerator to keep it always running until _stopSpawning is true;

This will need to be called start start. What we will do is in the Start() function we will start the coroutine.

The spawning will now continue for ever! What we need to do now is to make _stopSpawning true when the player dies. We do this by creating a public function called OnPlayerDeath and inside this function set _stopSpawning to true.

On the Player script we will need to call this function when the player dies. So first we need a reference to the Spawn Manager.

Next will be to find the SpawnManager and get the SpawnManager component. We will use GetComponent again, but this time we will use GameObject.Find().GetComponent. This will find the object that is passed into Find(). Always a good practice to null check, so we don’t get a crazy error.

We need to call the OnPlayerDeath function now. In the Damage function we created earlier, we need to call it.

And that’s it. The enemies will spawn until the player gets destroyed.

--

--

--

I am passonate on learning to program and use Unity to become a skillful Unity Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What Is Postman? Should You Be Using It?

為什麼我的PHP 的header 無法work? 原來是這邊需要修正!

為什麼我的PHP 的header 無法work? 原來是這邊需要修正!

Creating business value with IoT and big data analytics

Create a RESTfull API using Python and Flask (Part 1)

Understanding IAM in AWS

Using Nomad’s Vault integration

Not So Random Software #21 — Technical debt

Four Reasons I Chose to Become a Software Developer

Code sesh at the Central Library (Tulsa).

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
Tyler Smallwood

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

More from Medium

Day 101: Character Animation Part 4

Skeleton Enemy

Adding a User Interface to our prototype

Cinematography in Unity — Skyboxes