Designing Enemies With Class Inheritance

Objective: Understanding how Inheritance works and using it to design your enemies!

Now that we are taking our first steps in creating our enemies we need to create a new folder to store all our enemy scripts.

We are going to have one enemy class that defines all shared traits amongst the enemies. Then we will create individual enemy classes that will inherit from this base enemy class. Think of this class like a blueprint for what defines an enemy.

Open the script and remove start and update.

Now we create some variables to define our enemies. Think, “What do all the enemies have in common?” Health, speed, and gems that they would drop when defeated. Our enemies can also share methods, like an attack method.

We could attach this to an enemy and could define a unique enemy. However, we are going one step farther by having individual functionality.

If we have a spider and a moss giant, they would act very differently. Let’s create a moss giants script by right clicking the enemy folder and create new script.

Open the script and delete the start and update method. We want this class to inherit from the enemy class.

This is an empty class. If we attached this script to the character the inspector variables for health speed and gems are adjustable. This is because the moss giant inherits enemy class attributes.

If we created another script for a “Spider” and set it the same as moss giant by deleting the start and update and inherits from the enemy class. Attaching this to a blank object you will see that both spider and moss giant have the same properties. Though they have shared behaviors, their values are unique to themselves.

Now we need to understand access modifiers. We made our variables public, however, we don’t want any outside scrips to modify them. If we made them private our classes inheriting from enemy wont have access to them. We need to use the keyword protected. Protected is used so only the objects that inherit from this class can modify it. Best practice is to default with protected.

Great, now we have a shared understanding of how class inheritance works. We can advance on to the next tutorial where we will further our enemy design with Abstract classes! Don’t be afraid to experiment with your inheritance and I’ll see you in the next tutorial!