Objective: Implement an IDamageable interface in the enemies of a 2D game to indicate that they have health and are damageable.
In the last post I covered how to use abstract classes to design enemies in Unity. Now, it’s time to work with interfaces in order to let the player know that the enemies are damageable.
To start, let’s take a look at the enemies in our 2D game. Currently, we have a moss giant, a spider and a skeleton that patrol on certain areas of the level:
Now, in order to indicate that certain gameobjects are damageable (like our enemies), let’s create a new C# script named IDamageable:
Once created, let’s open the script and modify the IDamageable class to be of type interface:
Note: An IDamageable interface will allow us to force certain classes to implement properties and/or methods that are needed to handle damage.
Then, let’s declare a new property and a method to handle the damage in certain classes like the enemies:
This property will determine the amount of health that each class will have.
This method will take care of the damage application to the health within the class.
Once we save the interface, let’s open the class of an enemy and make sure to declare that it’s damageable by implementing the IDamageable interface:
You’ll notice that the class displays an error as soon as we declare that the class implements the interface:
This is due to the requirements of implementing the IDamageable interface. To fix it, we need to declare the respective health property and damage method within the class:
Once declared, we’ll see that the error disappears from the script. Then, let’s do the same to the other enemy classes:
And now, we’re able to declare what to do in each one of our enemies. For example, we can subtract a unit from the Health property in the Damage method:
This interface implementation allows us to call the Damage method without restrictions on what we want to damage in an attack. We could implement this interface in a wood box, an enemy or even the player. To use it, for example, we can get the IDamageable component from the collider on a collision and call the Damage method:
And that’s it, now we can use an interface to indicate that our enemies are damageable in Unity! :D. I’ll see you in the next post, where I’ll be showing a way to implement the hitbox detection within melee combat in Unity.