Unity HP System

HealthPlayer Script attached to the Player object. HealthPlayer derives from Hp class as it extends it and add more functionality.

using UnityEngine;

public class Hp : MonoBehaviour
{
    [SerializeField] protected int _maxHealth;
    protected int _health;

    void Start()
    {
        _health = _maxHealth;
    }

    public virtual void TakeDamage(int damage)
    {
        _health -= damage;
        if (_health <= 0)
        {
            Destroy(gameObject);
        }
    }

}

using System;

public class HealthPlayer : Hp
{
    public static event Action<int> HealthChange;

    void Start()
    {
        _health = _maxHealth;
        HealthChange?.Invoke(_health);
    }

    public override void TakeDamage(int damage)
    {
        _health -= damage;
        HealthChange?.Invoke(_health);
        if (_health <= 0)
        {
            Destroy(gameObject);
        }
    }

    public void AddHealth(int health)
    {
        _health = Math.Clamp(_health + health, _health, _maxHealth);
        HealthChange?.Invoke(_health);
    }
}

Health UI with image fill bar updated with Action event System

using System;
using UnityEngine;
using UnityEngine.UI;

public class HealthUI : MonoBehaviour
{
    [SerializeField] Image _healthImg;

    private void OnEnable()
    {
        HealthPlayer.HealthChange += OnHealthChange;
    }

    private void OnDisable()
    {
        HealthPlayer.HealthChange -= OnHealthChange;
    }

    void OnHealthChange(int health)
    {
        _healthImg.fillAmount = health / 10.0f; //10 because image consist of 10 blocks
    }
}
Scroll to Top