using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class HealthBar : MonoBehaviour { public Slider healthSlider; public TMP_Text healthBarText; HealthSystem playerHealthSystem; // Start is called before the first frame update private void Awake() { GameObject player = GameObject.FindGameObjectWithTag("Player"); if(player == null) { Debug.Log("player not found or missing tag on player"); } playerHealthSystem = player.GetComponent<HealthSystem>(); } void Start() { healthSlider.value = CalculateSliderPercentage(playerHealthSystem.currentHealth, playerHealthSystem.maxHealth); healthBarText.text = "HP " + playerHealthSystem.currentHealth + " / " + playerHealthSystem.maxHealth; } private void OnEnable() { playerHealthSystem.OnHealthChanged.AddListener(OnPlayerHealthChanged); } private void OnDisable() { playerHealthSystem.OnHealthChanged.RemoveListener(OnPlayerHealthChanged); } private float CalculateSliderPercentage(int currentHealth, int maxHealth) { return currentHealth / maxHealth; } private void OnPlayerHealthChanged(int newHealth, int maxHealth) { healthSlider.value = CalculateSliderPercentage(newHealth, maxHealth); healthBarText.text = "HP " + newHealth + " / " + maxHealth; } // Update is called once per frame void Update() { } }