74 lines
1.7 KiB
C#
74 lines
1.7 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
namespace OTG.Lab06.Core
|
|
{
|
|
[Serializable]
|
|
public sealed class ResourceStat
|
|
{
|
|
[SerializeField] private float maxValue = 100f;
|
|
[SerializeField] private float currentValue = 100f;
|
|
|
|
public event Action<float, float> Changed;
|
|
|
|
public float Current => currentValue;
|
|
public float Max => maxValue;
|
|
public float Normalized => maxValue <= 0f ? 0f : currentValue / maxValue;
|
|
|
|
public ResourceStat(float maxValue)
|
|
{
|
|
this.maxValue = Mathf.Max(1f, maxValue);
|
|
currentValue = this.maxValue;
|
|
}
|
|
|
|
public void Initialize(float value)
|
|
{
|
|
maxValue = Mathf.Max(1f, value);
|
|
currentValue = maxValue;
|
|
Changed?.Invoke(currentValue, maxValue);
|
|
}
|
|
|
|
public bool TrySpend(float amount)
|
|
{
|
|
if (amount <= 0f)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (currentValue < amount)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
SetCurrent(currentValue - amount);
|
|
return true;
|
|
}
|
|
|
|
public void Add(float amount)
|
|
{
|
|
if (amount <= 0f)
|
|
{
|
|
return;
|
|
}
|
|
|
|
SetCurrent(currentValue + amount);
|
|
}
|
|
|
|
public void Subtract(float amount)
|
|
{
|
|
if (amount <= 0f)
|
|
{
|
|
return;
|
|
}
|
|
|
|
SetCurrent(currentValue - amount);
|
|
}
|
|
|
|
private void SetCurrent(float value)
|
|
{
|
|
currentValue = Mathf.Clamp(value, 0f, maxValue);
|
|
Changed?.Invoke(currentValue, maxValue);
|
|
}
|
|
}
|
|
}
|