Interfaces vs Abstract classes in C# for Unity
Objective: Show the difference between using interfaces and abstract classes
Interfaces and abstract classes are similar in a way as they allow multiple classes to have similar functionality.
Interfaces are a great way to allow multiple classes access to the same functionality but implement them in different ways. This also allows those classes further scope as a class can only inherit from one other class but can implement as many interfaces as they like.
For my project, my different types of enemy all inherit from the base enemy class, but they also implement the interface for damage. This allows me to extend the functionality of the enemy classes while keeping them very similar.
When implementing an interface inside of a class, it is a contract between the two implying that the class will implement all of the methods and properties inside of the interface.
When inheriting from another class there is no such contract saying you need to implement the same functions and properties as the base class. You’re free to create new methods in the inheriting class, while in the interface, if you create a new method or property you will need to add the methods and properties to the classes that implement the interface.
The main benefit for me in using an interface for damaging game objects is that when the player hits an enemy or a box, the player doesn’t care what it has hit. If it has the component of type IDamageable, then it runs that classes implementation of the Damage method. This means, I do not need to do multiple compare tags and then get the components that have the scripts containing the damage method. I can just get the IDamageable component.
I have a script called Attack that is attached to the players sword. When the collision event is triggered, I get the IDamageable component of that object the sword has collided with and if it has that component, then run it’s Damage method. Using an interface in this way creates a loose coupling between the game objects as they don’t rely on each other to function.
I think both abstract classes and interfaces both have their benefits and drawbacks. I use both and pick the right ways to use them.