Creating a Modular Health System in Unity!

Marcus Ansley
3 min readAug 19, 2021

Recently worked on a more modular health system for this 3D shooter I’ve been working on for the GameDevHQ course. Essentially, rather than have the Player or Enemy class have their own separate health systems, both GameObjects will share the same Health script with different initial values (namely, their _maxHealth).

In case I forget to set the _maxHealth value in the Inspector, I also created a ‘SetDefaultHealth’ method which will set the max health to a standard, hard-coded value as a backup (_defaultHealth):

Next, we need a public Damage and Kill method. While I appreciate this isn’t a very fruitful use of them, I wanted to give interfaces a try with this. I created two dedicated scripts to house two custom interfaces: IKillable and IDamageable. Essentially, any script which is set to use either of these interfaces will need to include some specific methods in the script. I believe this can be handy when we want to standardise things, although I appreciate this is of less use in a single modular script such as this one.

For these two interfaces:

By including these interfaces after the MonoBehaviour inheritance statement, we then need to actually create these local methods in our script. So for Damage I’m just updating the remaining health using a damageAmount (passed in through the method) and am then checking to see if we’re out of health. If yes, the script will call the ‘Kill’ method which mostly just destroys the object this script is on (be that a player or an enemy). In the case we’re killing the Player, I’ve got the script to unparent the main camera before destroying them (otherwise we’ll end up destroying the camera itself, creating some runtime exceptions).

I’ll include the full script below:

The beauty of this is that we can now use this same health script on any damageable and killable object in the game, whether that’s an Enemy, Player, or perhaps some friendly NPC 😉 Definitely not a worthwhile use of interfaces, but I do want to get some practice in before I try to use them elsewhere.

--

--

Marcus Ansley

Game Developer | Game Design and Literature Graduate