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.

--

--

--

Unity Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Class Variables VS Instance Variables

The End and Beginning of A Journey: My Time at Fullstack Academy

If you only want slow, surface-level change, don’t read this

#4— The ESP32 with I2C Communication

Track Available COVID-19 Vaccine Slots in India with Python

READ/DOWNLOAD#> Professional Microsoft SQL Server

CS371-p Blog#2 Fall 2020, Saumyaa Krishnan

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
Mike Brisson

Mike Brisson

Unity Developer

More from Medium

Improving Upon Selection Highlighting in Our Game — Part 1

Unity Features 101: Assembly Definitions

Design Pattern: Command

Technologies for Video Game Production