IDamagable Interface in Unity

Objective: Creating and implementing an Interface!

It is now time to work on our damage system. for this damage system we don’t want it to be unique and specific to just attacking enemies. We want to be able to attack anything in our environment that could be damageable. To do this we are going to create an interface.

An interface is kind of like a contract that gets attached to an object and it forces the object to use its functions. The function we are making today is damage.

basically what will happen is if we swing our sword detect that an object has this interface implemented, we are going to call that function and then whatever object as this damage implementation is then going to handle the behavior.

To begin we need to create a new C# script named “IDamageable”

Traditionally the syntax for an interface is a capital I specifies it is an interface, then pascal casing just like we would when defining a class and usually end with “able”

Open the script and remove everything.

IDamageable will not inherit from anything.

This is not a class it is an interface.

This interface acts as a form of contract

We are going to define what an IDamageable interface is and any object that we want to apply this to is going to have to implement these methods.

What are the rules of this contract? Let’s say you must have a health variable, as well as a method named “Damage()”

There is no implementation in interfaces, it is very similar to how we force an implementation in our abstract class. Interfaces cannot use fields or constant variables, we will need to use properties. Properties are like variables only they use get-ers and set-ers.

This is an auto property

Now we have a contract called IDamageable that says you must implement a health property and a damage method. This is longer winded then we normally do for these tutorials so I will end this here and in the next tutorial we will cover how to use this interface! See you in the next tutorial!