Day 47: Refactoring Enemies!
Objective: Create new class that inherit from base Enemy script
When creating the second type enemy, I realized that it would get messy after awhile. I felt there was to many if statements in the code just to decide what the enemy would do.
To start off we need a script for the new enemy type. We’ll call this one ZigZagType(due to it’s movements, I need better names) and inside the script, we’ll replace monobehaviour with Enemy.
Changing monobehaviour to Enemy will cause the ZigZagType script to inherit everything from the Enemy script we created earlier. This includes movement, firing, OnTriggerEnter, etc.
The next thing we will do is decide which variable’s are needed only in the ZigZagType Class and move them over.
Next to follow up is figure out which variables we will need use in the Child Class. Once we figure it out, we’ll need to change them from private to protected, this allows for the child class to see them but not modify them.
Now for the functions, any function what we would want to modify in the child class will need to be changed from private to protected virtual void. This will allow us to use the function and override it as needed.
In the enemy class I changed the start function to a protected virtual function. I did this because the child class still needs to get a reference to the player and the animator objects but not modify them. The child class does however need to modify the start just a little for the way points.
In the Child class we will use protected override void Start. It’s wrote up as protected because the Base class is protected, they’ll need to be the same in this aspect. Next is override, this is only used when the function we are trying to override is set as virtual.
In this start function you’ll see we have the waypoints being instantiated and added to the array as shown in a previous article. You’ll also notice base.Start(); What this will do is run the function the same as it would on the base class, we don’t need to modify everything so that’s why its being used.
I’ve used this method for the firing, OnDeath, and CalculateMovement functions we have created in the past. We changed what was needed to be changed.
Only thing left to do is delete the enemy script from out ZigZag enemy prefab and add the ZigZagType Script to it. We’ll also need to assign the correct items that’s needed by this enemy.
It’s only a little different from the regular enemy type.
This was my attempt at refactoring into classes. I’ll use this system for any new enemies that we create along this path of learning Unity better!