IDamagable Interface in Unity
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 bepublic
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 aclass
: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 thevirtual
keyword. This will be useful, for example, when adding animations or particle systems.Health
andhealth
values behave differently.
In the code above,Health
will take thehealth
value as a starting value, andDamage()
will decreaseHealth
, buthealth
will remain the same.
If you want to update thehealth
value, you’ll need to addhealth = Health
inDamage()
inEnemy
script.
It depends on the required implementation.