Files
WaveDefender/Assets/Scripts/PlayerHealth.cs

50 lines
1.1 KiB
C#
Raw Normal View History

2026-04-17 10:38:43 +01:00
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.");
}
}