72 lines
2.0 KiB
C#
72 lines
2.0 KiB
C#
|
|
using System;
|
||
|
|
using OTG.Lab06.Core;
|
||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
namespace OTG.Lab06.Characters
|
||
|
|
{
|
||
|
|
public sealed class PlayerStats : MonoBehaviour
|
||
|
|
{
|
||
|
|
[SerializeField] private float health = 100f;
|
||
|
|
[SerializeField] private float mana = 100f;
|
||
|
|
|
||
|
|
private ResourceStat healthStat;
|
||
|
|
private ResourceStat manaStat;
|
||
|
|
|
||
|
|
public event Action<float, float> HealthChanged;
|
||
|
|
public event Action<float, float> ManaChanged;
|
||
|
|
|
||
|
|
public float Health { get { EnsureInitialized(); return healthStat.Current; } }
|
||
|
|
public float MaxHealth { get { EnsureInitialized(); return healthStat.Max; } }
|
||
|
|
public float Mana { get { EnsureInitialized(); return manaStat.Current; } }
|
||
|
|
public float MaxMana { get { EnsureInitialized(); return manaStat.Max; } }
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
EnsureInitialized();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Start()
|
||
|
|
{
|
||
|
|
HealthChanged?.Invoke(Health, MaxHealth);
|
||
|
|
ManaChanged?.Invoke(Mana, MaxMana);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void TakeDamage(float amount)
|
||
|
|
{
|
||
|
|
EnsureInitialized();
|
||
|
|
healthStat.Subtract(amount);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Heal(float amount)
|
||
|
|
{
|
||
|
|
EnsureInitialized();
|
||
|
|
healthStat.Add(amount);
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool SpendMana(float amount)
|
||
|
|
{
|
||
|
|
EnsureInitialized();
|
||
|
|
return manaStat.TrySpend(amount);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void RestoreMana(float amount)
|
||
|
|
{
|
||
|
|
EnsureInitialized();
|
||
|
|
manaStat.Add(amount);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void EnsureInitialized()
|
||
|
|
{
|
||
|
|
if (healthStat != null && manaStat != null)
|
||
|
|
{
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
healthStat = new ResourceStat(health);
|
||
|
|
manaStat = new ResourceStat(mana);
|
||
|
|
healthStat.Changed += (current, max) => HealthChanged?.Invoke(current, max);
|
||
|
|
manaStat.Changed += (current, max) => ManaChanged?.Invoke(current, max);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|