Health System

Reusable health component with damage, healing, invincibility frames, and events.

File
HealthSystem.cs
Unity
2022.3+
Level
beginner
Size
2.4 KB · 78 lines
Added
2026-02-21
License
MIT
View source

No APIs that Unity 6.0 to 6.6 made obsolete or removed. How this is checked

What it adds to your GameObject

A MonoBehaviour component: attach it to a GameObject. This is the Inspector you get, read from the source: 7 serialized fields with their defaults.

Inspector
Script HealthSystem
Health
Max Health 100
Current Health 0
Invincibility
Invincibility Duration 0.5
Events
On Health Changed (float, float)
List is Empty
On Death ()
List is Empty
On Damaged ()
List is Empty
On Healed ()
List is Empty

When to use it

Essential for virtually any game with damageable entities — platformers, shooters, RPGs, tower defense, and survival games. Use this on players, enemies, destructible objects, or even bosses. It is the universal building block that other combat scripts (damage popups, health bars, weapon systems) connect to via events.

Setup

  1. Attach to any GameObject that needs health (player, enemies, destructibles)
  2. Configure max health and invincibility duration
  3. Hook up events in the inspector or via code
  4. Call TakeDamage() and Heal() from other scripts

Features

  • Damage and healing with clamped health values
  • Invincibility frames with configurable duration after taking damage
  • UnityEvent callbacks for health changed, damaged, healed, and death
  • Public properties for HealthPercent, IsAlive, and IsInvincible checks
  • SetMaxHealth with optional heal-to-full for level-up scenarios
  • ResetHealth method for respawn or checkpoint restoration

Inspector fields

Every field Health System exposes in the Inspector, with the default it starts at.

FieldTypeDefaultGroup
Max HealthmaxHealthfloat100Health
Current HealthcurrentHealthfloat0Health
Invincibility DurationinvincibilityDurationfloat0.5Invincibility
On Health ChangedOnHealthChangedUnityEvent<float, float>No listenersEvents
On DeathOnDeathUnityEventNo listenersEvents
On DamagedOnDamagedUnityEventNo listenersEvents
On HealedOnHealedUnityEventNo listenersEvents

Public API

What other scripts can call on HealthSystem.

MemberReturns
TakeDamage(float damage)void
Heal(float amount)void
SetMaxHealth(float newMax, bool healToFull = false)void
ResetHealth()void
CurrentHealth propertyfloat
MaxHealth propertyfloat
HealthPercent propertyfloat
IsAlive propertybool
IsInvincible propertybool

Common mistakes

Calling TakeDamage() with a negative value does nothing because the script guards against it — use Heal() instead. If OnDeath doesn't seem to fire, check that invincibilityDuration isn't set too high, preventing subsequent hits from registering. Remember that events set in the Inspector are per-instance, so prefab overrides may not carry your event wiring to spawned copies.

Source code

HealthSystem.cs, 78 lines, MIT licensed. Paste it into a new C# file of the same name.

HealthSystem.cs
C#
using UnityEngine;
using UnityEngine.Events;

public class HealthSystem : MonoBehaviour
{
    [Header("Health")]
    [SerializeField] private float maxHealth = 100f;
    [SerializeField] private float currentHealth;

    [Header("Invincibility")]
    [SerializeField] private float invincibilityDuration = 0.5f;
    private float invincibilityTimer;

    [Header("Events")]
    public UnityEvent<float, float> OnHealthChanged; // current, max
    public UnityEvent OnDeath;
    public UnityEvent OnDamaged;
    public UnityEvent OnHealed;

    public float CurrentHealth => currentHealth;
    public float MaxHealth => maxHealth;
    public float HealthPercent => currentHealth / maxHealth;
    public bool IsAlive => currentHealth > 0f;
    public bool IsInvincible => invincibilityTimer > 0f;

    private void Awake()
    {
        currentHealth = maxHealth;
    }

    private void Update()
    {
        if (invincibilityTimer > 0f)
            invincibilityTimer -= Time.deltaTime;
    }

    public void TakeDamage(float damage)
    {
        if (!IsAlive || IsInvincible || damage <= 0f) return;

        currentHealth = Mathf.Max(0f, currentHealth - damage);
        invincibilityTimer = invincibilityDuration;

        OnHealthChanged?.Invoke(currentHealth, maxHealth);
        OnDamaged?.Invoke();

        if (!IsAlive)
            OnDeath?.Invoke();
    }

    public void Heal(float amount)
    {
        if (!IsAlive || amount <= 0f) return;

        currentHealth = Mathf.Min(maxHealth, currentHealth + amount);

        OnHealthChanged?.Invoke(currentHealth, maxHealth);
        OnHealed?.Invoke();
    }

    public void SetMaxHealth(float newMax, bool healToFull = false)
    {
        maxHealth = newMax;
        if (healToFull)
            currentHealth = maxHealth;
        else
            currentHealth = Mathf.Min(currentHealth, maxHealth);

        OnHealthChanged?.Invoke(currentHealth, maxHealth);
    }

    public void ResetHealth()
    {
        currentHealth = maxHealth;
        invincibilityTimer = 0f;
        OnHealthChanged?.Invoke(currentHealth, maxHealth);
    }
}