The Magic of Interfaces to bring the PAIN.
At this point, I need to create a damage system for my enemies. However what if I have more than one type of enemy? What about if I want other objects to be damaged? I don’t want to make a new damage script for every separate object or enemy so it is time to learn about interfaces.
An interface is like a contract, and if the object that has it applied, it must have the required items from the interface.
To begin, we create a script called IDamageable (Starting with a capital I to denote it being an interface) and instead of inheriting from monobehavior, we do as in the image. “public interface IDamageable”.
We then can add our first requirements. An auto property for Health, and a Damage method.
By adding the IDamageable interface to my Skeleton script as above…
like a contract, this script must now have both the Health property as well as a Damage method, or else the script will error.
So what actually makes this special? Well…
In my attack script, I can actually check for the IDamageable interface in and enemy or object using a GetComponent. So when my sword attack enters a collider, it will attempt to get the IDamageable component and store it in “hit”. If it isn’t null, it will actually call the function in whatever the object was!
Previously I had mainly used tags to denote what triggers what, however with more and more enemies in a game that can be quite the hassle. With the interface, my attack doesn’t know if it hit a object, or a enemy, but all that matters is that the object has IDamageable and the hit will be registered!
C# never ceases to amaze me in what it can do and I hope it never stops.
See you next post!