Files
VRProject/Assets/_Scripts/EnemyHealth.cs
ohgushiyuga 9864b95a91 HPbarzissou
2026-08-27 17:59:06 +09:00

82 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<float, float> OnHealthChanged; // ★追加:HP変更イベント(現在HP, 最大HP)
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 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);
}
}