Designing Enemies using Abstract Classes

When creating logic for enemy types, it’s common for your enemies to share traits such as Health, Strength, and Attack(). Simple inheritance can be used across your enemy classes to help streamline your code…but what if you want to enforce the use of some methods while allowing them to be customized if necessary?

This is where abstract classes shine! They focus on the accountability of an interface while simultaneously allowing for the flexibility of traditional class inheritance.

Let’s start with a simple enemy class:

In this example, we have set up a simple class with health and speed variables along with an Attack method. We can adjust the health and speed between enemy types as well as call Attack from any class that inherits from enemy like this:

If we want to make sure that all classes that inherit from Enemy implement the Attack method, we use the keyword “abstract”. We define the class itself as abstract as well as any methods (without definitions) we want to be utilized:

Note: Abstract classes CAN NOT be instantiated; They can only be inherited from.

Then we override the abstract method(s) in the child classes:

In this case, the zombie class inherits from Enemy which in turn inherits from MonoBehaviour. This give the flexibility of traditional inheritance while making sure that child classes implement specific functionality.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store