Creating a Modular Health/Damage System

On my previous article, I have tried to explain how to create an enemy follow system without using NavMesh. Now that the enemies can follow the player, it is time to create a health and damage system. Certainly, enemies will not be the only objects that will hold a health variable for handling damages in the game. Aside from the player, we might add some objects that are damageable in the game.

A typical solution for this might be creating an universal Health script and attaching it to every object that will require a health variable. By using SerializeField attribute, we can insert custom values for each game object using the Health script. Since all of them will be seperate instances, it will not be any problem.

However, I am going to stick with interfaces. If you have been following up my articles, you might have seen my article on Interfaces — if not, you can click here for it.

I have created an IDamageable interface and added a void Damage method with an int parameter. To make sure that each of the objects implementing the IDamageable interface has a Health variable, I have also added a Health property.

IDamageable Interface

Of course, in order to implement the IDamageable interface, I have updated both Enemy and Player scripts.

Enemy Script — Health
Enemy Script — Damage Method

Previously, I have created a seperate Shoot script for Player shooting. As I am still in the beginning of the project, I simply created the Damage method in a way that will damage the enemy on each click. Later on, I will add the Bullets and handle the damage with a cooldown system.

After hitting the enemy 10 times (had set its health to 100), it simply gets destroyed:

Unity Developer