Enemy Abstract Class

Hal Brooks
3 min readOct 23, 2021

--

Objective: Create a enemy abstract class and use it to move Moss Giant.

MossGiant inherits a required Update method from Enemy.

An abstract class cannot be a component of a game object, rather an abstract class is used to force inheritance. Shown below is the C# script for the Enemy abstract class. The protected variables are like private variables, but inheritable. The virtual method, Attack(), contains code for all game objects inheriting from Enemy. The abstract Update() declaration cannot have code in enemy but requires this method exist in the game object inheriting from Enemy, here MossGiant. Unity will throw an error if a void Update() method does not exist in MossGiant script.

Enemy abstract class script.

The MossGiant script inherits the abstract Enemy class through : Enemy class declaration, shown below. The protected variables can be accessed for each game object, because they are declared in Enemy. The MossGiant can access the Attack() method of Enemy and also inherits Monobehavior through Enemy. The override is used to declare the required void Update() method.

MossGiant inherits the public and protected variables and methods from the Enemy abstract class.

The inherited variables can be assigned in the MossGiant script. Those assigned in the inspector through [SerializeField] are shown below. The other variables are assigned through code in void Start(), as shown above. The animation requires access to both the Animator and SpriteRenderer for the Sprite of the Moss_Giant. The animation of the giant is beyond the scope of this article.

Moss giant inherited variables.

The method for MoveGiant() is shown below is unique to MossGiant. This method moves the giant to the target position. When the giant reachs the target the nextTarget is passed to the coroutine, IdleTime(), to set the newTarget and allow the giant to idle for 5 seconds. The giant can now walk between pointA and pointB.

MoveGiant() method in MossGiant script.

The coroutine, IdleTime, is shown below and used to allow the giant to wait at each way point, and is also unique to MossGiant.

IdleTime coroutine in MossGiant script.

The abstract class sets expectations for variables and methods of objects that are similar. The ability to assign code to a virtual method, such as in Attack(), within the abstract class differentiates an abstract class from an interface.

--

--

No responses yet