IDamagable Interface in Unity

Hernando Nieto Jaramillo
2 min readSep 4, 2021

After setting up the skeleton enemy to be identified by the sword, we face a challenge: how can we make the same mechanic work for all the enemies?

One way could be this:

But if you have some experience in coding, you’ll find some critical issues about game programming design:

  • This code is difficult, if not impossible to maintain or upgrade in a very high scale, because you’ll need to the same last 3 lines of code for each enemy type, and they could be dozens or hundreds of them
  • the ApplyDamage() method must be public to be accessed, and it’s a non-recommended practice due to possible unwanted access from other scripts

To avoid both issues, we use Interfaces

  • Create a new script, call it IDamageable
  • declare as an interface instead of a class :
    public interface IDamageable

An interface works like a contract. Any script that inherits from the interface must implement its content, including properties (not variables) and methods.

Further info can be found on internet

And do this for all the other enemies, in this case 3 ones.

There is another way that I prefer instead: as the enemies inherit from Enemy script, it will inherit IDamageable

Do the same as above, but in Enemy script

Code should look like this:

Keep in mind:

  • //1 and //2 do the same
  • public void Damage() will be implemented (executed) in the same way for all the enemies. If you want to customize it in any of them, you’ll need to add the virtual keyword. This will be useful, for example, when adding animations or particle systems.
  • Health and health values behave differently.
    In the code above, Health will take the health value as a starting value, and Damage() will decrease Health, but health will remain the same.
    If you want to update the health value, you’ll need to add
    health = Health in Damage() in Enemy script.
    It depends on the required implementation.

--

--