IDamagable Interface in Unity

We always talk about finding common points to optimize the work and write code that is easily reusable.

I already talked about class inheritance, this tool is very useful but it has a limit to one. In the C# language, we can’t inherit from several classes at the same time and for this reason, we use interfaces.

Interfaces are always defined as a contract between an object and its user.
An interface is a collection of methods and properties because it is not possible to use typed variables, which must exist inside the class that will implement the interface.

In this example I have created the signature of a method and a property that must be implemented in the class that will call this interface, otherwise, the compiler will report an error.

With this system in this specific case my IDamageable interface allows me to have a script that I can connect to any type of object in the scene that can suffer damage and has a Health element. Not only the player and the enemies but also all the objects that I want to make destructible in the scene.

To implement an interface after the class from which we inherit if we have one, we insert a comma and write the name of the interface that we have to implement. For nomenclature, all interfaces are named with “I” and end with “-able”

project manager by day, unity developer by night