Files
Echo/Assets/_Project/Scripts/UI/VitalsHUD.cs
T
2026-07-08 20:42:51 +08:00

81 lines
2.1 KiB
C#

using Michsky.UI.Reach;
using Player;
using UnityEngine;
using UnityEngine.Serialization;
namespace UI
{
public class VitalsHUD : MonoBehaviour
{
[Header("References")]
public PlayerVitalsSystem target;
[FormerlySerializedAs("healthBar")] public ProgressBar thirstBar;
public ProgressBar hungerBar;
public ProgressBar sanityBar;
bool isBound;
void OnEnable()
{
if (target == null)
{
target = FindObjectOfType<PlayerVitalsSystem>();
}
Bind();
RefreshAll();
}
void OnDisable()
{
Unbind();
}
void Bind()
{
if (isBound) return;
if (target == null) return;
target.health.onValueChanged.AddListener(OnThirstChanged);
target.hunger.onValueChanged.AddListener(OnHungerChanged);
target.sanity.onValueChanged.AddListener(OnSanityChanged);
isBound = true;
}
void Unbind()
{
if (!isBound) return;
if (target == null) return;
target.health.onValueChanged.RemoveListener(OnThirstChanged);
target.hunger.onValueChanged.RemoveListener(OnHungerChanged);
target.sanity.onValueChanged.RemoveListener(OnSanityChanged);
isBound = false;
}
void RefreshAll()
{
if (target == null) return;
UpdateBar(thirstBar, target.health);
UpdateBar(hungerBar, target.hunger);
UpdateBar(sanityBar, target.sanity);
}
void UpdateBar(ProgressBar bar, VitalStat stat)
{
if (bar == null) return;
if (stat == null) return;
bar.minValue = stat.minValue;
bar.maxValue = stat.maxValue;
bar.SetValue(stat.currentValue);
}
void OnThirstChanged(float _) => UpdateBar(thirstBar, target.health);
void OnHungerChanged(float _) => UpdateBar(hungerBar, target.hunger);
void OnSanityChanged(float _) => UpdateBar(sanityBar, target.sanity);
}
}