94 lines
2.3 KiB
C#
94 lines
2.3 KiB
C#
using UnityEngine;
|
|
|
|
public class EnemyHealth : MonoBehaviour
|
|
{
|
|
public float maxHealth = 100f;
|
|
public float currentHealth;
|
|
|
|
[Header("Death Settings")]
|
|
public bool destroyOnDeath = true;
|
|
public float deathDelay = 0.1f;
|
|
|
|
private bool isDead = false;
|
|
|
|
void Start()
|
|
{
|
|
currentHealth = maxHealth;
|
|
}
|
|
|
|
public void TakeDamage(float amount)
|
|
{
|
|
if (isDead) return;
|
|
|
|
currentHealth -= amount;
|
|
Debug.Log($"{gameObject.name} took {amount} damage! HP: {currentHealth}/{maxHealth}");
|
|
|
|
// Flash red on hit
|
|
StartCoroutine(HitFlash());
|
|
|
|
if (currentHealth <= 0f)
|
|
{
|
|
Die();
|
|
}
|
|
}
|
|
|
|
System.Collections.IEnumerator HitFlash()
|
|
{
|
|
Renderer[] renderers = GetComponentsInChildren<Renderer>();
|
|
if (renderers.Length == 0) yield break;
|
|
|
|
// Store original colors
|
|
Color[] originalColors = new Color[renderers.Length];
|
|
for (int i = 0; i < renderers.Length; i++)
|
|
originalColors[i] = renderers[i].material.color;
|
|
|
|
// Flash all parts white-red
|
|
for (int i = 0; i < renderers.Length; i++)
|
|
renderers[i].material.color = new Color(1f, 0.3f, 0.3f);
|
|
|
|
yield return new WaitForSeconds(0.08f);
|
|
|
|
// Restore
|
|
if (!isDead)
|
|
{
|
|
for (int i = 0; i < renderers.Length; i++)
|
|
{
|
|
if (renderers[i] != null)
|
|
renderers[i].material.color = originalColors[i];
|
|
}
|
|
}
|
|
}
|
|
|
|
void Die()
|
|
{
|
|
isDead = true;
|
|
Debug.Log($"{gameObject.name} KILLED!");
|
|
|
|
if (destroyOnDeath)
|
|
{
|
|
// Quick death: disable collider immediately, destroy after delay
|
|
Collider col = GetComponent<Collider>();
|
|
if (col != null) col.enabled = false;
|
|
|
|
// Optional: add a little "pop" by scaling down
|
|
StartCoroutine(DeathEffect());
|
|
}
|
|
}
|
|
|
|
System.Collections.IEnumerator DeathEffect()
|
|
{
|
|
float timer = 0f;
|
|
Vector3 startScale = transform.localScale;
|
|
|
|
while (timer < deathDelay)
|
|
{
|
|
timer += Time.deltaTime;
|
|
float t = timer / deathDelay;
|
|
transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t);
|
|
yield return null;
|
|
}
|
|
|
|
Destroy(gameObject);
|
|
}
|
|
}
|