Designing Enemies using Abstract Classes

Objective: Setup Enemies using Abstract Classes

Our Enemies are going to share some similar traits such as speed and health. Rather than implementing the same logic in each type of enemy we can use inheritance from a bass enemy class that the Moss Giant and Spider enemies all share.

To start we create a bass enemy script and create serialized protected int variables for health, speed and gems. We then create scripts for the MossGiant and Spider which inherit from Enemy instead of MonoBehaviour.

Having shared code is great but each type of enemy will likely have its own logic to implement. We want to enforce this logic as in each enemy needs to run its own Update(override). To do this we make the Enemy class abstract and create an abstract Update method that forces all classes that inherit from Enemy to create their own Update.

Once the above additions to the bass Enemy class, changing public class to public abstract class and adding the abstract Update, the MossGiant class gives an error because it does not implement the inherited abstract Enemy.Update().

To fix this, a public override needs to be added.

Developer