74 lines
1.7 KiB
C#
74 lines
1.7 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
public class EnemyHealth : MonoBehaviour, IDamageable
|
|
{
|
|
[SerializeField] private float maxHealth = 100f;
|
|
[SerializeField] private float knockbackDuration = 0.5f;
|
|
|
|
public float CurrentHealth { get; private set; }
|
|
public bool IsDead { get; private set; }
|
|
|
|
public event Action<float> OnKnockbackRequested;
|
|
public event Action OnDeath;
|
|
|
|
private EnemyAI enemyAI;
|
|
private Animator anim;
|
|
private Collider col;
|
|
|
|
private static readonly int DeadHash = Animator.StringToHash("Dead");
|
|
|
|
private void Awake()
|
|
{
|
|
CurrentHealth = maxHealth;
|
|
enemyAI = GetComponent<EnemyAI>();
|
|
anim = GetComponent<Animator>();
|
|
col = GetComponent<Collider>();
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
if (enemyAI != null)
|
|
{
|
|
OnKnockbackRequested += enemyAI.TriggerKnockback;
|
|
OnDeath += enemyAI.DisableAIOnDeath;
|
|
}
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
if (enemyAI != null)
|
|
{
|
|
OnKnockbackRequested -= enemyAI.TriggerKnockback;
|
|
OnDeath -= enemyAI.DisableAIOnDeath;
|
|
}
|
|
}
|
|
|
|
public void TakeDamage(DamageInfo damageInfo)
|
|
{
|
|
if (IsDead) return;
|
|
|
|
CurrentHealth = Mathf.Max(0f, CurrentHealth - damageInfo.amount);
|
|
|
|
if (CurrentHealth <= 0f)
|
|
{
|
|
Die();
|
|
}
|
|
else
|
|
{
|
|
OnKnockbackRequested?.Invoke(knockbackDuration);
|
|
}
|
|
}
|
|
|
|
private void Die()
|
|
{
|
|
if (IsDead) return;
|
|
IsDead = true;
|
|
|
|
if (anim != null) anim.SetTrigger(DeadHash);
|
|
if (col != null) col.enabled = false;
|
|
|
|
OnDeath?.Invoke();
|
|
Destroy(gameObject, 3.0f);
|
|
}
|
|
} |