56 lines
1.5 KiB
C#
56 lines
1.5 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
public class Health : MonoBehaviour
|
|
{
|
|
[SerializeField] private int _maxHealth = 30;
|
|
private int _currentHealth;
|
|
|
|
public int MaxHealth => _maxHealth;
|
|
public int CurrentHealth => _currentHealth;
|
|
public float Ratio => _maxHealth > 0 ? (float)_currentHealth / _maxHealth : 0f;
|
|
public bool IsDead => _currentHealth <= 0;
|
|
|
|
public event Action<int, int> OnHealthChanged;
|
|
public event Action OnDied;
|
|
|
|
private void Awake()
|
|
{
|
|
_currentHealth = _maxHealth;
|
|
}
|
|
|
|
public void TakeDamage(int amount)
|
|
{
|
|
if (amount <= 0 || IsDead) return;
|
|
|
|
int previous = _currentHealth;
|
|
_currentHealth = Mathf.Max(_currentHealth - amount, 0);
|
|
OnHealthChanged?.Invoke(_currentHealth, _maxHealth);
|
|
|
|
if (_currentHealth <= 0 && previous > 0)
|
|
OnDied?.Invoke();
|
|
}
|
|
|
|
public void Heal(int amount)
|
|
{
|
|
if (amount <= 0 || IsDead) return;
|
|
|
|
_currentHealth = Mathf.Min(_currentHealth + amount, _maxHealth);
|
|
OnHealthChanged?.Invoke(_currentHealth, _maxHealth);
|
|
}
|
|
|
|
public void ResetHealth()
|
|
{
|
|
_currentHealth = _maxHealth;
|
|
OnHealthChanged?.Invoke(_currentHealth, _maxHealth);
|
|
}
|
|
|
|
public void SetMaxHealth(int newMax, bool fill = true)
|
|
{
|
|
_maxHealth = Mathf.Max(newMax, 1);
|
|
if (fill) _currentHealth = _maxHealth;
|
|
else _currentHealth = Mathf.Min(_currentHealth, _maxHealth);
|
|
OnHealthChanged?.Invoke(_currentHealth, _maxHealth);
|
|
}
|
|
}
|