2D Mobile Game: Enemy Class Setup

Intro

In this article, we are going to setup our Enemy Class and how to inherit properties created in this class for other enemy scripts.

Enemy Class

We are going to have at least 3 different enemies for our game all of which will share similar properties. All of the enemies will have int variables for health, speed, and gems (when destroyed they will drop gems). Lets create an Enemy Class that will allow separate enemy scripts to inherit these properties.

In order for other enemy scripts to inherit these int variables from the enemy class, we will need to make the variables public and not private. But, having variables public allows other scripts to access them and we only want to our enemy scripts to access them. This is where we can use protected variables. Protected variables allow other enemy scripts to inherit these properties while still keeping them private. So, only scripts that are inheritance of the enemy class can access these variables. Lastly, we can give them a SerializedField attribute which allows us to see these protected variables in the Inspector.

Moss Giant Script

We are going to create the first enemy script, MossGiant, and initially the script inherits MonoBehaviour. But, we want to inherit the properties from the Enemy Class script.

To do this, we replace MonoBehaviour with Enemy, and inherit the health, speed, and gem int variables.

Since we gave them the SerializedField attribute in the Enemy Class script and we didn’t declare any variables in the Moss Giant script, you can see how theses properties have been pass from the Enemy Class script to the Moss Giant script.

--

--

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