67 lines
1.5 KiB
C#
67 lines
1.5 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
public class PlayerHealthController : MonoBehaviour
|
|
{
|
|
public static PlayerHealthController Instance { get; private set; }
|
|
|
|
[SerializeField] private int maxHealth = 100;
|
|
private int currentHealth;
|
|
|
|
public event Action<int, int> OnHealthChanged;
|
|
public event Action OnPlayerDied;
|
|
|
|
public int CurrentHealth => currentHealth;
|
|
public int MaxHealth => maxHealth;
|
|
public bool IsDead => currentHealth <= 0;
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance != null && Instance != this)
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
else
|
|
{
|
|
Instance = this;
|
|
}
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
currentHealth = maxHealth;
|
|
OnHealthChanged?.Invoke(currentHealth, maxHealth);
|
|
}
|
|
|
|
public void TakeDamage(int damageAmount)
|
|
{
|
|
if (currentHealth <= 0) return;
|
|
|
|
currentHealth = Mathf.Max(0, currentHealth - damageAmount);
|
|
OnHealthChanged?.Invoke(currentHealth, maxHealth);
|
|
|
|
if (currentHealth <= 0)
|
|
{
|
|
Die();
|
|
}
|
|
}
|
|
|
|
public void Heal(int healAmount)
|
|
{
|
|
if (currentHealth <= 0) return;
|
|
|
|
currentHealth = Mathf.Min(maxHealth, currentHealth + healAmount);
|
|
OnHealthChanged?.Invoke(currentHealth, maxHealth);
|
|
}
|
|
|
|
private void Die()
|
|
{
|
|
OnPlayerDied?.Invoke();
|
|
if (UIController.Instance != null)
|
|
{
|
|
UIController.Instance.ShowGameOverScreen();
|
|
}
|
|
}
|
|
}
|
|
|