fgm24/Assets/Scripts/Misc/HealthBar.cs

44 lines
1.0 KiB
C#

using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
[SerializeField]
private HealthComponent attachedHealth;
[SerializeField]
private Image healthBarImg;
[SerializeField]
private Color healthLeftColor, unusedHealth;
[SerializeField]
private bool disableOnDeath = true;
private void OnEnable()
{
if (healthBarImg != null)
attachedHealth.OnHealthChange.AddListener(UpdateHealthBar);
}
private void OnDisable()
{
if (healthBarImg != null)
attachedHealth.OnHealthChange.RemoveListener(UpdateHealthBar);
}
private void UpdateHealthBar(float prevHealth, float newHealth)
{
float percent = newHealth / attachedHealth.getMaxHealth();
healthBarImg.fillAmount = percent;
if (disableOnDeath && percent <= 0)
{
for (int i = 0; i < transform.childCount; i++)
{
transform.GetChild(i).gameObject.SetActive(false);
}
}
}
}