initial commit
This commit is contained in:
66
Assets/Scripts/PlayerHealthController.cs
Normal file
66
Assets/Scripts/PlayerHealthController.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user