Designing Enemies using Abstract Classes
Objective: Learn how to use an abstract class to help design your enemies!
In the last tutorial we went over using inheritance to design enemies, and not we are going to compound this with the use of abstract classes.
If an enemy wanted to use the inherited bass attack method with additional code, this is where a virtual method comes in. Virtual methods allow you to overwrite the parent attack method and can still use the implementation.
To create this we are going to change the “public void attack” to “public virtual void attack”
The virtual keyword will allow you to rewrite the implementation. If we navigate to our spider script we can overwrite the attack method.
What if the spider wanted some implementation details from the parent class? Before calling our code that is unique to the spider you can type “base” which will give you access to the parent class “Enemy”
This will also come in handy when we create an abstract class. The goal of this is we want the enemy to define other enemies. When we create 50 enemies we want to make sure they have certain methods. So now we need to figure out what methods are going to be on each object.
Each character is going to have AI between moving waypoints which will be controlled through an update method. We could force an update method on them. We could have the AI code all through this shared class as an enemy but they are all not going to have the same AI, they all aren’t going to share the same waypoints.
One of the things we can do here is force and update method on them so they can control their own destiny for updating their AI. This is where Abstract classes come in.
If we make the enemy class an abstract class we can create abstract methods.
We can not replace our virtual update with an abstract method.
With this abstract method added, our enemies that inherit from this code will now have an error. This is because they don’t have an update method.
You cannot just call an update method, it must override the parent object.
What’s happening here is each enemy is going to have it’s own unique update that is unique to itself while still sharing the common traits of our enemy class. Now, not only do they share common enemy code, they all have their own unique implementations to void update.
We can now create unique AI code that is going to be specific to each individual enemy.
Side note: If you followed along than you will notice that we no longer see our shared members in the inspector. This is because we made them protected, Simply use the serializefield to see them and modify them in the inspector!
This has been a little more technical than our usual tutorials but I felt this was an important topic to outline. Don’t be afraid to experiment with using abstract classes, and I’ll see you in the next tutorial!