Designing Enemies as Abstract Classes

Esteban Ibarra
3 min readAug 4, 2021

--

Whenever we write a script, we’re creating classes. For example, the player script we created for the player object that made them run, jump, and attack is known as the Player class. Most scripts/classes that we write are meant to be instantiated along with objects and essentially provide a set of directions/actions for those objects. There is a type of class however that isn’t meant for action, but to provide a template or be an outline for sub-classes, these are known as Abstract Classes.

I’m going to get into the subject as a semi-tutorial, but if you want a fantastic nutshell-overview, I highly suggest Mohammed Hijazis article on Abstract Methods.

In our current game example, we’re going to have a few enemies, each on has information like speed, health, gems, and Attack method. If we had 30 or 50 enemies, writing this same info for each enemies script would get really redundant! Fortunately, We can make an Enemy abstract class that every enemy can draw from and will inherit all the information!

We can also include a damage function for when the player hits the enemy, but what if there are other things like barrels, collectibles, and other random objects that can be destroyed. They’re not enemies, but we can use something called an Interface, which is basically a contract that says to an object, “Hey, you MUST implement this method!”. Let’s say that method is IDamagable. If the player has something coded in its swing that it’s looking for the damage function, it will find it. The player doesn’t need to care what it hits, it only knows it hits something, the individual class will deal with it its own way.

As a simple example, let’s make an enemy script and put it in its own directory.

And let’s populate the script with a few variables and an attack method.

Normally, this is the point where we would attach this script to our enemy, but let’s do it a new way. We’ll create a new enemy script for the Moss_Giant and we’ll attach this one to our Moss Giant enemy:

Now we’ll change the inheritance from Monobehaviour to the Enemy script we just created.

Now if we select our Moss Giant, we have our Enemy variables available!

Pretty exciting stuff! We’ll delve a little deeper tomorrow!

--

--

Esteban Ibarra
Esteban Ibarra

Written by Esteban Ibarra

cartoonist, game artist, and wanabe gamedev.

No responses yet