ai and player nd health scripts
This commit is contained in:
49
Assets/Scripts/PlayerHealth.cs
Normal file
49
Assets/Scripts/PlayerHealth.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
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.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user