diff options
| author | Weicao-CatilGrass <1992414357@qq.com> | 2026-05-12 08:49:44 +0800 |
|---|---|---|
| committer | Weicao-CatilGrass <1992414357@qq.com> | 2026-05-12 08:49:44 +0800 |
| commit | b1a45c232474e99b52eadc43406ab7de15b7ee95 (patch) | |
| tree | 9b821060928ab5272ff739dfe3ba462f8f3db034 /Assets/Scripts/DamageVolumeSystem/HealthData.cs | |
| parent | cb06c001d8c99bcf2d4fd16db4b8443f12b3cf60 (diff) | |
Add health system
Diffstat (limited to 'Assets/Scripts/DamageVolumeSystem/HealthData.cs')
| -rw-r--r-- | Assets/Scripts/DamageVolumeSystem/HealthData.cs | 95 |
1 files changed, 95 insertions, 0 deletions
diff --git a/Assets/Scripts/DamageVolumeSystem/HealthData.cs b/Assets/Scripts/DamageVolumeSystem/HealthData.cs new file mode 100644 index 0000000..8da1e5f --- /dev/null +++ b/Assets/Scripts/DamageVolumeSystem/HealthData.cs @@ -0,0 +1,95 @@ +using System; +using UnityEngine; +using UnityEngine.Events; + +namespace DamageVolumeSystem +{ + [Icon("Assets/Scripts/DamageVolumeSystem/Icon/HealthData.png")] + public class HealthData : MonoBehaviour + { + public int defaultHealth = 5000; + public int maxHealth = 5000; + + public UnityEvent<Damage> onAid = new(); + public UnityEvent<Damage> onHurt = new(); + public UnityEvent onDead = new(); + + private int _health; + + public int Health + { + get => _health; + set + { + var offset = value - _health; + var offsetAbs = Mathf.Abs(offset); + switch (offset) + { + case > 0: + Aid(new Damage + { + Group = 12, + Force = offsetAbs, + Direction = Vector3.zero + }); + return; + case < 0: + Hurt(new Damage + { + Group = 12, + Force = offsetAbs, + Direction = Vector3.zero + }); + break; + } + } + } + + private void Start() + { + _health = defaultHealth; + } + + private void Reset() + { + var newHealth = Mathf.Clamp(defaultHealth, 0, maxHealth); + SetHealth(newHealth); + } + + public void Aid(Damage damage) + { + AddHealth(damage.Force); + onAid.Invoke(damage); + } + + public void Hurt(Damage damage) + { + ReduceHealth(damage.Force); + onHurt.Invoke(damage); + + if (_health <= 0) + onDead.Invoke(); + } + + public static HealthData operator +(HealthData a, Damage b) + { + a.Aid(b); + return a; + } + + public static HealthData operator -(HealthData a, Damage b) + { + a.Hurt(b); + return a; + } + + private void SetHealth(int newHealth) + => _health = Mathf.Clamp(newHealth, 0, maxHealth); + + private void AddHealth(int newHealth) + => _health = Mathf.Clamp(_health + newHealth, 0, maxHealth); + + private void ReduceHealth(int newHealth) + => _health = Mathf.Clamp(_health - newHealth, 0, maxHealth); + } +} |
