Esteban Ibarra

Aug 17, 2021

3 min read

IDamagable interface in Unity

We’ve developed a system that we can now hit anything with our sword, but we don’t want to write a case-by-case damage system for each enemy, that would be too much work. Instead, we can write an all-encompassing system that we can place on any damageable object, to do that, we create an Interface.

Dramatic reproduction of an interface contracting a method.

An interface is like a contract, and when attached to an object it says ‘Hey, you MUST implement these functions!’.

That function for us will be damage.

Let’s create a new C# Script called IDamagable. Whenever you create a new interface, good practice always has you begin it with the capital letter I, and end it with ‘able’.

Template for an interface: I-name-able

Next, we’ll remove the start and update functions. And since IDamagable won’t need to inherit from monobehaviour, remove that as well. We’re going to change IDamagable from a class to an interface.

Now we’re going to define what IDamagable is, and any method we attach this too will have to conform to it!

So what will our IDamagable interface require? we’ll need a health variable for sure, and a Damage method, and since this is an interface, we don’t implement it with the brackets, we just define it with a semicolon. Note: You can’t just define a variable as a field, but as a property. Properties are like variables, but they use getters and setters:

While we could attach IDamagable to our Enemy script, which would then pass that contract to every enemy that bases itself on it, While shared functionality is valid and could work, let’s do it individually first. We’ll attach our IDamagable to the Moss_Giant and how you do that is place a comma next to the class it inherits, and then include IDamagable.

A class can inherit from one class, but multiple interfaces.

As soon as we hit save, we now get an error because we haven’t implemented the mandatory items IDamagable requires.

Saving the script and then giving unity a few seconds to process them shows us a screen free of errors!

While our enemy class does have a health variable, having the IDamagable require a Health variable just assures us that every item that uses IDamagable has it. For example, our enemies have a health variable, but the boxes that we plan to make breakable currently do not. IDamagable will assure us they will.

Let’s create an example with the Moss_Giant by bringing in the enemy class initialize.

Actually, just to keep things clean, let’s remove the health line for now. We’ll keep the Init function, and initialize the other two enemies with the same obligatory code:

And now we’re ready to inflict damage on all our enemies! Tomorrow we’ll put the interface into action!