GameDevHQ Crash Course #35 Abstract Classes and Interfaces
Last time(https://arrotal.medium.com/gamedevhq-crash-course-33-abstract-classes-f58be65dca70) I talked about the benefits of abstract classes, lets put them into practice and compare them to interface classes.
We have added a bunch of functions into our base enemy abstract class, these are all classes our enemies. Now to use that we go to our Skeleton class and we replace Monobehaviour with EnemyBase, The name of our abstract class.
Now that we have added that we have all these premade functions that we don’t have to rewrite for every enemy we add. We can add this to 100s of enemies with no problem and save ourselves thousands of lines of code.
However we can only inherit 1 abstract class to our skeleton class.
You can however inherit multiple interfaces, interfaces work slightly different from an abstract class, we do not create parented functions, you create a contract with the inheriting class.
This interface we are creating the contract of the inheriting class that it will have a public Health property.
We then inherit the Idamagable class to our Skeleton class same way as we inherit the abstract class, you will encounter an error in your script at the inheritance line if you do not add the contracted parts, this is especially useful if you need certain functions in a class for that class to function correctly, IE an enemy would require a health component so it can be damaged and destroyed.
Speaking of, another benefit of creating a generic interface class, you can use it to filter collisions.
with this, as long as the object that our attack collided with has the IDamagable contract(IE our skeleton we just made) then we call the Damage function that we know it will have because if it has the IDamagable interface inheritance it has to have a Damage function that takes an int. This will help keep your scripts from those stray errors because you forgot to implement a required function and tried to call something that wasn’t there.