Day 22: Creating an Enemy Base Class and using Inheritance to create different Enemy objects

Philip Johnson
3 min readJul 29, 2021
In between the last segment and now I added a simple sword swing animation to set up for our attack system in the future

Objective: To create a base class for our enemy objects to inherit common code so that we can create several different enemies without redundantly rewriting the same code in every class.

In our game we want to have enemies that the player can destroy by either jumping on them or by other means(i.e. shooting them with a projetile, melee combat, and so on). Instead of having to rewrite the same code that deals with properties shared by all objects that are enemies, we can create a base class for our enemy objects to inherit from. This is one of the core concepts in object oriented programming. Our enemy objects will inherit the implementation created in the parent class, and we can create abstract and virtual methods that give us the power of manipulating methods from ther parent class to suit each enemy type.

an abstract class creates an interface with a child class and requires the child class to implement the abstract methods from the parent class

Another type of method that can be overwritten by a child class are virtual method. Overriding a parent class method maintains internal implementation of the parent method if desired. So because out Update method in the parent class is abstract in an abstract parent class, we MUST implement Update into each child class as such: Private Override Void Update().

In the image above we are looking at a child class that inrehits from the Enemy base class. The base class itself inherits from MonoBehaviour so we can still use the base methods that we are used to such as Update and OnTriggerEnter. Because we inherit from the Enemy class we MUST implement the public override void Update().

The update method of the child class “Giant Rat” will have its own unique implementation. Here we are calculating movement similar to how we handle our moving platforms.

The Attack method seen here is overriding the public virtual method in the parent class. The base keyword is used to implement the logic created in the parent class, which is optional.

This is a good way to set up a base class for our enemies. In the gif above we see our movement code at work and the giant rat is seen patrolling left and right. I wont go into detail about how to set up the Animator at this point as we should all know the basics of the mecanim state machine.

--

--