Interfaces for damage in Unity

Daniel Kirwan
3 min readSep 9, 2021

Objective: Implement an interface to damage game objects in Unity

In your game you will want to at some point damage an enemy or a breakable object. The best way to implement this is for the weapon or bullets that are hitting other objects, is to not care about what they’re hitting.

An interface is a contract of functionality between the interface and the class that implements it. It must include all the properties and methods of the interface otherwise there will be errors. Interfaces are a great way to provide the same functionality across multiple classes that are not related to each other.

To create an interface in Unity, create a C# script and call it IDamageable. Open it up and make a couple of changes.

  1. Change class to interface
  2. remove monobehaviour and the : from the name

I have added a property of Health with a getter and setter. I then added a method called Damage.

To implement the interface in a class you need to add it in a similar way to inheritance.

As you can only inherit from one class an interface is a great way to extend functionality of a class.

Once the interface name is added you will most likely see errors appearing, this will be because you have not implemented the methods or properties from the interface.

You can leave the method body empty if you have not got any implementation yet. I have my implementation, this will take 1 health off of the object that has been hit. In this case it is the skeleton.

Now that I have implemented the method and property inside the skeleton I can quickly move this over to the other enemies and have them take damage as well.

All I then need to do is make sure that the other enemies have a health value and then hit them.

And that’s it for implementing an interface for damaging game objects.

--

--