Nerd For Tech
Published in

Nerd For Tech

Designing Enemies using Abstract Classes

Now that we have our player unity created, let’s take a look at how we can go about making enemy’s within our game. We could go about and create them all as their own script’s and enter in all of their own individual attributes:

However, when you look at how the different enemy types are set up, they all have the same sort of information. Now, with just a couple different units in place, it isn’t too bad but if we were to implement dozens of different enemy types, the amount of script work needed would add up pretty quick. To alleviate the amount of work we would have to put in, we can create an abstract class to code in all of the shared attributes of our enemies, and then assign values and such to those particular enemies:

To start, let’s create a script for the enemy class along with our moss giant:

Within our Moss_Giant script, all we are going to do is change it from MonoBehaviour to Enemy after we created our enemy script properties and attach it to our giant object within unity:

As we can see, even though our Giant script is empty, the 1 change to have it pull from the Enemy script allows us to use the public int values we set up. Now, when we are using this type of script behaviour, using public is generally not best practice, as we want to keep the values hidden from other classes that do not need access to this information. To do that, we can use a different method of setting up the restrictions other than public or private:

With the protected restriction, it allows us to call upon the variable with any class that is calling upon that particular one.
Next, let’s take a look at adjusting our void to a virtual one. What this allows us to do is have our own methods for a certain behaviour, like attack, but we can also make alterations to it based on the enemy we are adjusting:

As we can see, we are still calling upon the My Name Is, however with the spider class we call an additional method.
Next, we will alter our Enemy class into an abstract class, and create an abstract void update. This will have it so that anything we create using the enemy behaviour will be forced to implement an override to that particular void:

With this method, we can use it to be sure that every time we create a new enemy, we are sure to add in all of the needed behaviours to make our new enemy function proper. Now that we have looked into how we can construct an abstract class, we will look into creating the individual behaviours for the various enemy types we plan to implement into our game.



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