Making Enemies

David Little
4 min readJun 8, 2021

…in the game, not in life, of course.

To continue developing the space-shooter game we’re going to add enemies. To start they are just going to be cubes, like our main character, and they will be what we’re shooting at throughout the game as we progress through with play.

We start by adding another cube and naming it ‘Enemy’.

Then, make the new cube a little bit smaller by setting the scale to, say, 0.80. Next create a new material for the enemy that has a red albedo and is named ‘Enemy-mat’. Finally, drag the new material onto the red cube.

You’ll next create a prefab of the cube by dragging it on the Project panel.

Then, drag the newly created prefab back onto the Hierarchy panel and delete the original cube that you created there.

I know, it looks like you’re just doing the physical version of a loop but it makes better sense in practice after you’ve gone through it a few times. It’s needed in order to create an object that you can create more instances of in your game, if needed. Then, if you need to edit your object you just do it to the prefab, in stead of having to go and edit every instance of the object now cloned thought the game.

After this, create a new C# script called ‘Enemy’ and open it in your editor, in this case, Visual Studio. Once created, be sure to drag the new script onto the Enemy prefab. Double-click the script and we’ll begin defining the Enemy’s attributes.

We want the enemy to move from the top of the screen to the bottom at a certain speed to create a top-down scrolling shooter. So, the first thing we set for our enemy game object is going to be its speed variable, which will look like this…

Next we need to define how that variable is to be used. We’ll use our old friend Time.deltaTime to do that. And, that looks like this…

Finally, if we miss when firing at the enemy, we don’t want the enemy game object to continue on forever. After a while we would end up with a lot of these objects cluttering up memory. We would rather recycle them. The simplest way is to just put them back at the starting line after they fall past a predetermined y-value, and we can do that in the Update like this…

Further, we want these ‘recycled’ enemies to have a random starting point along the width of the display. We need to add code to provide a randomized x-value. This is done with Random.Range, where you define a minimum and maximum value for x. If it is an integer value the range is the minimum up to the maximum minus one. If it is a float value the range is the minimum up to and including the maximum. We will be using the later.

The full script for the enemy game object looks like this…

Then, to finish, save the script and test it out in Unity.

--

--