Power of Inheritance

Hal Brooks
3 min readOct 26, 2021

--

Objective: Use Enemy abstract class to derive the behavior for two new enemies.

Skeleton and Moss Giant (top) & Spider (bottom) all animated using abstract Enemy class script.

Modify the abstract Enemy class to initialize the anim, spriteRenderer, and target using an Init() method that is called in the void Start() of Enemy, see below.

Init() method is called in void Start() of Enemy abstract class.

Change the code public abstract void Update() to that shown below. The virtual designation allows code in the base class Enemy to be inherited by derived scripts: MossGiant, Spider and Skeleton.

Virtual void Update() method

The virtual method MoveMonster() moves the code previously used in MossGiant script into the Enemy script.

Virtual MoveMonster() method is inherited by all derived scripts.

Each new enemy needs the same hierarchical structure as shown below for Moss_Giant, Spider and Skeleton.

Hierarchy for Moss Giant, Spider and Skeleton enemies.

The Moss_Giant_Enemy, shown below, as well as Spider_Enemy and Skeleton_Enemy all require the components exemplified below.

Required components for derived enemies.

The MossGiant script is now simply that shown below. The use of public override void Init() allows custom code for each enemy. In this case, MossGiant is just using the base.Init() method shown above. Similar scripts are created for Spider and skeleton deriving thier behavior from enemy instead of MonoBehavior; however, they still inherit MonoBehavior from the base Enemy.

Each new enemy also needs an Animator, like that shown for Skeleton Sprite, with an Idle trigger parameter used to exit Walk, while Idle uses has exit time to transition to Walk. Setting up the animations is outside the scope of this article.

The Enemy script expects the Sprite, child(0), to contain the animator script. The Animator and Sprite Renderer must be on the Sprite.

Sprite for Spider.

This modular design allows the rapid creation of many enemies to inherit behavior from an Enemy abstract class, each with the potential to use override to customize individual enemies.

--

--

No responses yet