Updating player health using event in Unity



Player.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using UnityEngine;
 
public class Player : MonoBehaviour
{
    public static event Action<int> _HealthUpdateEvent;
    int health = 100;
 
    public void GainHealth()
    {
        health = Mathf.Clamp(health + 10,0,100);
        if(_HealthUpdateEvent!=null)
        {
            _HealthUpdateEvent(health);
        }
    }
 
    public void LooseHealth()
    {
        health = Mathf.Clamp(health - 10, 0, 100);
        if (_HealthUpdateEvent != null)
        {
            _HealthUpdateEvent(health);
        }
    }
}

HealthDisplay.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using UnityEngine;
using UnityEngine.UI;
 
[RequireComponent(typeof(Text))]
public class HealthDisplay : MonoBehaviour
{
    Text healthValueText;
 
    void Awake()
    {
        healthValueText = GetComponent<Text>();
    }
 
    void OnEnable()
    {
        Player._HealthUpdateEvent += UpdateHealth;
    }
 
    void OnDisable()
    {
        Player._HealthUpdateEvent -= UpdateHealth;
    }
 
    void UpdateHealth(int value)
    {
        healthValueText.text = value.ToString("000") + " / 100";
    }
}