50 lines
1.1 KiB
C#
50 lines
1.1 KiB
C#
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
|
|
/// <summary>
|
|
/// Simple player health component. Attach to the Player GameObject.
|
|
/// </summary>
|
|
public class PlayerHealth : MonoBehaviour
|
|
{
|
|
[Header("Health")]
|
|
public float maxHealth = 100f;
|
|
|
|
[Header("Events")]
|
|
public UnityEvent onDeath;
|
|
public UnityEvent<float> onHealthChanged; // passes current health
|
|
|
|
public float CurrentHealth { get; private set; }
|
|
public bool IsDead { get; private set; }
|
|
|
|
void Awake()
|
|
{
|
|
CurrentHealth = maxHealth;
|
|
}
|
|
|
|
public void TakeDamage(float damage)
|
|
{
|
|
if (IsDead) return;
|
|
|
|
CurrentHealth = Mathf.Max(0f, CurrentHealth - damage);
|
|
onHealthChanged?.Invoke(CurrentHealth);
|
|
|
|
if (CurrentHealth <= 0f)
|
|
Die();
|
|
}
|
|
|
|
public void Heal(float amount)
|
|
{
|
|
if (IsDead) return;
|
|
|
|
CurrentHealth = Mathf.Min(maxHealth, CurrentHealth + amount);
|
|
onHealthChanged?.Invoke(CurrentHealth);
|
|
}
|
|
|
|
void Die()
|
|
{
|
|
IsDead = true;
|
|
onDeath?.Invoke();
|
|
Debug.Log("[PlayerHealth] Player died.");
|
|
}
|
|
}
|