Modular Health System in Unity

Paul Killman
2 min readJan 11, 2024

The latest challenge in my current project is to create a modular health system for the player and enemies. It needs to be a script that can be attached players, characters or enemies in the game.

The basic requirements are simple:

  • Create a script that can be attached to anything that can take damage.
  • Have variables to store Max, Min and Current health.
  • Create a damage method that can be accessed by whoever or whatever is causing the damage.
  • Calculate the health of whoever is receiving the damage.
  • Check to see if the characters health is below the minimum health value.
  • Create a death method that destroys the current character.

The first requirement was easy. I created a C# script and named it Health.

Inside of the script, I created three variables to store the Max, Min and Current health of the character. I made the damage stats integers because I didn’t think that the character could take part of a health point as damage. I made Max and Min health easy to modify in the Inspector.

[SerializeField]
private int _maxHealth;
[SerializeField]
private int _minHealth;
private int _currentHealth;

The next step was to create a damage method that can be accessed by whoever or whatever is causing the damage. I created a public method named TakeDamage. This method receives a damage amount when it is called.

    public void TakeDamage(int damage)
{
_currentHealth -= damage;
if(_currentHealth < _minHealth)
{
Die();
}
}

This method also meets the next two requirements which were calculate health and check for death.

The final requirement was to create a method for the character to die. I could have put it in the TakeDamage method, but I thought that down the road that I would probably want to get fancy and add in a death animation and possible some kind of particle effect. I created a method named Die.

    public void Die()
{
Destroy(this.gameObject);
}

The few lines of code in this script are a solid beginning to a universal health system that can easily be attached to anything that takes damage and can die or be destroyed.

Here is the complete script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Health : MonoBehaviour
{
[SerializeField]
private int _maxHealth;
[SerializeField]
private int _minHealth;
private int _currentHealth;

void Start()
{
_currentHealth = _maxHealth;
}

void Update()
{

}

public void TakeDamage(int damage)
{
_currentHealth -= damage;
if(_currentHealth < _minHealth)
{
Die();
}
}

public void Die()
{
Destroy(this.gameObject);
}
}

--

--