Time to make some abstract enemies.

Objective: Designing enemies using abstract classes.

Rose Owen
3 min readAug 26, 2021

--

Image by Lucas Benjamin found on unsplash.com

So far in this journey, when we have wanted to add in a new enemy, we added more methods to an already cluttered script. By using something called an Abstract class and combined with some class inheritance, we can make a script for each enemy and make things neater.

To start off, let’s take a look at the class inheritance side of things. This can be done super easily and is really useful. Say you want all your enemies to have health, speed and how many gems they drop when they die. Instead of having to code all that in each and every enemy, we can use class inheritance.

First, we need a base script to hold all the common parts for the enemy, this can even include methods.

You can have the variables as either public or protected, where public will let anyone change the values, and protected is like saying private on each script. Since we want the different enemies to have access to these values we can’t use private since it will limit it to just the enemy script, hence why the “protected” in this case.

With all that done we can now go to one of our enemies. To inherit from the enemy class all we need to change is MonoBehaviour to Enemy and we are done.

As you can see, we have full access to the variables we made in the enemy class too without having to add them to the moss giant.

Now to change to an abstract class for the enemy, to do this all we need to do is add in “abstract” before the class on the enemy.

Now we can make some abstract methods, this makes it so the enemies that inherit from this class must have the method but have to implement it themself.

In this example we are using the update method, all that was added was again “abstract”, this time before the void. Now when we change back over to the moss giant we should have an error.

We can use the auto-fix function in Visual studios or just add in the public override void Update(){} ourselves.

Virtual lets us choose to override but abstract forces us to override. This can be handy, after making 20 enemies and one isn’t working because you forgot to add a method or oh I have an error, oh yeah… adds method. I know what one I would choose.

And with that, we have a basic overview of adding in an abstract enemy class that we can build on later to make all our enemies from.

--

--

Rose Owen

Game Developer in the making~