Daily progress: Merging Enemy Code into the base class
If we have similar behaviours in our enemies like as is what is happening with our skeleton and Moss Giant, we can carefully combine them into the enemy base class for even more organized code.
Let’s copy our skeletons ‘InCombat’ flip code and place it onto the Moss Giant:
And if we run our code, we can see that the shared logic works identically.
Putting the code into our current enemy movement, we see there’s already another distance variable defined for when the player moves away from the enemy, but it’s fine, we can actually just use that instead and combine the if statements.
We’ve deleted our code in the moss monster, but let’s remove it from our skeleton code too:
Our skeleton behaves as if the flip code was running in its own script!
If there’s 2 or more enemies that share very similar behavior, then it may be wise to go ahead and include it in the base class, remember that functions can always be overriden by the sub-class.
As a side note, while we may be able to include the IDamagable into the base class, we would lose the ability to know which enemy we’re hitting so at the moment, it’s better to just include it individually on each enemy script.