Day 8: Enemy Setup

Anthony Pietrzak
2 min readJul 8, 2021

Today, we’ll be taking a look at creating enemies for you to fight in the space shooter game!

GOAL: Create an enemy object and establish it’s behavior.

First, create a new cube object in Unity, and name it Enemy. We also want to create a new material object, and call it Enemy_mat. Apply the mat to the enemy object you created, and then drag the enemy object in the Game Hierarchy to the prefabs folder. This is how you create a prefab object. Then create a new C# script called Enemy. This is how your hierarchy of objects should look right now.

Object, Prefab, Mat, and Script.

We want the enemy to move down, but also teleport to the top of the screen if it reaches the bottom of the screen. Using the code below does just that, as the if statement handles the teleportation of the enemy, and the private float and first transform statement handle the movement downward.

Results:

But we don’t want the enemy to go on a straight line as shown. We want it to be randomly spawning on the X-axis. Let’s add that in as an extra statement to our code. Random.range does just that for us, so let’s utilize it. Replace the code within the if statement to this.

Results:

It’s all over the place now!

There! Now the cube teleports around the X-axis when it respawns. Next time, we’ll look at how to make lasers collide with the enemy, and also how to setup the destruction of an enemy.

--

--