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 float MaxHealth => maxHealth; public bool IsDead { get; private set; } public event Action OnHealthChanged; // ★追加:HP変更イベント(現在HP, 最大HP) public event Action 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(); anim = GetComponent(); col = GetComponent(); } private void Start() { OnHealthChanged?.Invoke(CurrentHealth, maxHealth); } 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); OnHealthChanged?.Invoke(CurrentHealth, maxHealth); // ★HP変更をUIに通知 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); } }