Objective: Implement the IDamageable interface!
In our last tutorial we created an IDamageable interface and now it is time to implement. We currently have a contract called IDamageable that says you must implement a health property and a damage method.
We need to implement this onto whoever we want to be able to use this contract. Anything our sword is going to hit is going to basically implement the IDamageable interface.
Let’s give our enemies unique implementation of damage. We can choose to do this on the enemy script, however, if we did then they are going to have the shared functionality. Maybe the spider has a very different damage logic than other. I am going to do this individually for my monsters but the option is always available for you to choose.
My Moss Giant enemy inherits from the enemy class.
To add an implementation of an interface all we have to do is add a comma and the name of the interface.
You can only inherit from one class but you can implement as many interfaces as you want. We are given an error because we are not adhering to the contract. We need to have a health property and a damage method.
There, now the error is gone!
Our enemy class has it’s own int health. The reason we force an int health with the IDamageable is to force other objects that don’t have health to have health. Using our initialization function we can assign the interface health to the enemy’s health.
If we wanted to add a parameter to damage method, it needs to be added on IDamageable.
The damage method will now be called whenever the player’s sword collides with the object that has the IDamageable interface. For an example we can use a Debug log to show every time it is called.
Now you know how to set up an IDamageable Interface. You can now add this to any object. Don’t be afraid to experiment with interfaces and I’ll see you in the next tutorial!