Modular Health System In Unity

Jon Jenkins
2 min readOct 12, 2021

Below we have a Red Block representing an enemy in Unity. You can see we shoot it until it “dies”. Here I will explain an easy way to implement a health system in Unity.

A modular health system is one that can work with many elements in the game, specifically players and enemies. We need to write some code that will be generic enough so that we can attach it to any game object and it will work.

My solution is below:

Basically, we define a few variables: max health, min health, and current health. We add [SerializeField] so that they are accessible in the inspector.

Basically when the scripts starts, we will set the current health to the max health, so that our game object starts out at full health.

Now every time our game object is damaged by something, the damager will get a reference to this game object and call the Damage method. The damage method will subtract the damage amount from the current health. It will then check to see if the current health has gone below the minimum health allowed. If so, the game object will be destroyed.

An example of how this would be called from outside is below:

So basically here, if the player clicks their left mouse button we will “shoot” by ray casting. If the ray hits something that has the health component, the Damage method is called. This is done in the last line: health.Damage(50).

The beauty of this system is that this Health script can be added to anything that has health and can be damaged. We don’t need to define a separate health script for every type of game object, unless we need something more complex for a certain object.

That’s all there is to it.

--

--

Jon Jenkins

A Unity Developer, interested in all things Unity.