Abstract Classes continued — The Virtual Method.

Esteban Ibarra
4 min readAug 5, 2021

Yesterday we created an Abstract Enemy class and attached it to our Moss_Giant. Let’s create a few more example enemies to share a few more examples. I’ll create a couple more empties and call them Spider and Skeleton and create scripts for them too. Just to make things visually more appealling, I’ll put the appropriate sprites in the empties.

Now we have 3 enemies all inheriting from the same Enemy script and all have the same variables for speed, health and gems! Useful!

Let’s say I want to set the speed of our Moss Giant right now, we’re going to run into our first problem regarding child classes.

We’re not able to modify the speed variable because I set it as private, meaning any changes can only be made in the original enemy script.

Reviewing variable scopes, Private variables can only be accessed from inside their classes, public variables can be accessed from anywhere, but what if we don’t want our variables to be modified by just any class? Enter the protected variable class, this will allow child classes to modify parent classes items, so let’s fix our original enemy script.

And now let’s change the variable.

Now it’s available to us!

Ok, having the same variables is all fine and good, but what if we want, say, a different attack method for our spider than everyone else? You can do that with Virtual Methods! using the virtual before the method's type will allow you to rewrite it. So let’s say as an example, all our enemies have a default of saying “BASH AND SMASH”.

So in our enemy script, we’ll have this in our Attack function:

And all of our enemies will invoke the Attack function:

Ok, let’s say we want our skeleton to have a different attack method where he’ll say “I NEED MILK!”

First, we’ll need to change our original attack method and convert it to a virtual method.

Now we can change the skeletons attack method, but just changing what’s inside isn’t enough, you need to specify you’re going to change it with override!

And there you have it! The original Enemy Attack script is now replaced with a brand new version we just wrote!

But what if we wanted to use the original attack method as well? Use base.Attack()!

So now our skeleton Bashes and Smashes and immediately needs a refill of milk. Makes sense, I imagine skeletons would need immediate refreshment after a hefty swing of an axe!

What’s also pretty cool is if you have something you want everyone to execute in the update, you can make it virtual:

Let’s say the spider has an override for the update:

This will allow spider to run its own update code along with the original enemy abstract classes.

Tomorrow, we’ll get into how abstract classes can be like interfaces and force another class to implement a method.

--

--