Creating an IDamagable Interface in Unity
Interfaces are a great way to modularize or decouple your code. If you look up the definition of an interface, you will likely be greeted with some form of this text:
“An interface is a contract between an object and it’s user…”
So what does this mean? Essentially, an interface is just a collection of method and property declarations that must exist within any class that implements the interface. For example, if an interface has a Health property and is implemented by a Player class, the player class must also have the Health property.
In order to create an interface, we create a new script and change it from a class to an interface:
With the interface created, we can now add any methods, properties, events, indexers that we need. In this example, we’ll add a Health property as well as an Attack() method:
Let’s create an Enemy class that will implement this interface:
In the above example, our Zombie class is inheriting from Enemy and implementing IDamageable. Classes in C# can only inherit from a single class (one parent) but can implement many interfaces.
By implementing IDamageable, we are guaranteeing that our Zombie class will have everything that the interface being implemented will have. Now instead of referencing the specific enemy type or even the Enemy class, we can simply create an instance of IDamageable and we will have access to any class that implements IDamageable:
We can now implement this interface in anything that needs to take damage…from a crate, to an enemy, to a vehicle! This is the power of interfaces!