Inheritance from Core System- Game Dev Series 102

Objective: create abstract class to enemies as modular system.

Moss Giant has a modular script!

Modular is a key system in game design. Create modular system would allow game designer easily to expand the elements within the game.
For example, if you have 10 different types of enemy in your game, thus they all have some common variables such as health, walking speed, etc. You would never want to create these methods one by one. They all share some same types of variable, why not make them follow 1 core script?

In this article, we will take a peek of how to inheritance from core script to create modular system.

About inheritance

First we need to know about what is “inheritance”. Create a new script and called is “Enemy”. This would be the core script of our enemies.
Inside this script, we can create some variables and methods that every enemy would have.

Once we have the core script, create another script for 1 of your enemies. In here, I would create a Moss Giant.
Open the MossGiant script, if we want to use all the data from Enemy script, we can simply replace “MonoBehaviour” to “Enemy”, which is the script we just created.

Once we inheritance Enemy, we can easily to call the variables or methods from it.

Virtual method

When creating some methods in core script, we can use “virtual” as a definition to method. If it is a virtual method, it can be used directly, or override some or all of the contents.
For example, we will create an Attack() method in Enemy script.

All the enemies might have some common attacking method, might be not.
We can separate these difference by using “override” in script that inheritance.

base.Attack() is what it inheritance from Enemy script. If you do not need the function in it, you can wipe this line of code to create its own Attack().

Abstract class

Abstract method can be used with abstract class
To create abstract class, simply add “abstract” in front of class definition.

When create an abstract method inside an abstract class, it means that method should be in every script that inheritance from this class.
There is no need to create contents of abstract method.

In this example, if there is no Update() method in MossGiant script, it would shows error.

Once we create an override Update() method, it would be all right.

Abstract method would be used to create the same methods to all scripts that inheritance from core that would be easy to identify or locate the functions that are in common.

Protect your variables

When we create public variables in abstract class, it might be adjusted accidentally.
To prevent this situation and can also be used in inheritance scripts, we can use “protected” to variables.

These variables can only be used from scripts that inheritance from it.
If you want to adjust these variables in editor, simply add “[SerializeField]” to each variable.

A passionate gamer whose goal is to work in video game development.