fgm24/Assets/Scripts/Misc/HealthBar.cs

44 lines
1.0 KiB
C#
Raw Permalink Normal View History

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