first commit
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
using OTG.Lab06.Characters;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace OTG.Lab06.UI
|
||||
{
|
||||
public sealed class ResourceBarUI : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private PlayerStats playerStats;
|
||||
[SerializeField] private Image fill;
|
||||
[SerializeField] private Text valueLabel;
|
||||
[SerializeField] private bool useMana;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
Subscribe();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
Unsubscribe();
|
||||
}
|
||||
|
||||
public void Bind(PlayerStats stats, bool mana)
|
||||
{
|
||||
Unsubscribe();
|
||||
playerStats = stats;
|
||||
useMana = mana;
|
||||
Subscribe();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void Subscribe()
|
||||
{
|
||||
if (playerStats == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (useMana)
|
||||
{
|
||||
playerStats.ManaChanged += OnChanged;
|
||||
}
|
||||
else
|
||||
{
|
||||
playerStats.HealthChanged += OnChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private void Unsubscribe()
|
||||
{
|
||||
if (playerStats == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
playerStats.ManaChanged -= OnChanged;
|
||||
playerStats.HealthChanged -= OnChanged;
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
if (playerStats == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
OnChanged(useMana ? playerStats.Mana : playerStats.Health, useMana ? playerStats.MaxMana : playerStats.MaxHealth);
|
||||
}
|
||||
|
||||
private void OnChanged(float current, float max)
|
||||
{
|
||||
float normalized = max <= 0f ? 0f : Mathf.Clamp01(current / max);
|
||||
if (fill != null)
|
||||
{
|
||||
fill.type = Image.Type.Filled;
|
||||
fill.fillMethod = Image.FillMethod.Horizontal;
|
||||
fill.fillOrigin = (int)Image.OriginHorizontal.Left;
|
||||
fill.fillAmount = normalized;
|
||||
}
|
||||
|
||||
if (valueLabel != null)
|
||||
{
|
||||
valueLabel.text = $"{Mathf.RoundToInt(current)} / {Mathf.RoundToInt(max)}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user