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

Carb Manager Clone

Creating a Discord Bot using Python

Bash for Beginners Part 1: Anatomy of the command line

Components at Scale: Implementing Storybook

What transpired during Google I/O Extended Cebu 2019

Unity: Creating enemy explosion effect

Installing CUDA 10.1 on Ubuntu 20.04

like Pi network its also the same just join as soon as possible

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

Switching Character Control in Unity: Part II, Implementation

An animated gif. The window is split. On the left, a camera looks at a tank as it first moves towards the camera. The tank then stops and the turret begins to rotate left and right. The animation finishes with the turret elevating towards the camera. On the right, the same scene is shown from the perspective of a camera following the tank. After the tank finishes moving, the camera switches to one looking just over the turret and rotates with the turret as it first trains, then elevates.

A Noisy World — Obsidian Server’s Minecraft-Like World Generation Pt. 4

Singleton Design Pattern Unity

What’s new in PVS-Studio in 2021?