Files
OTG_2/Assets/_Scripts/EnemyTarget.cs
T

99 lines
2.4 KiB
C#
Raw Normal View History

2026-06-04 17:37:58 +03:00
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class EnemyTarget : MonoBehaviour
{
public float maxHealth = 100f;
public float currentHealth;
public Text healthText;
public Renderer targetRenderer;
private Color originalColor = Color.white;
private Collider targetCollider;
private Coroutine flashRoutine;
private void Awake()
{
if (targetRenderer == null)
targetRenderer = GetComponentInChildren<Renderer>();
targetCollider = GetComponent<Collider>();
if (targetRenderer != null)
originalColor = targetRenderer.material.color;
ResetTarget();
}
private void LateUpdate()
{
if (healthText != null && Camera.main != null)
healthText.transform.rotation = Quaternion.LookRotation(healthText.transform.position - Camera.main.transform.position);
}
public void TakeDamage(float amount)
{
if (currentHealth <= 0f)
return;
// Targets can be reused in tests through ResetTarget without rebuilding the scene.
currentHealth = Mathf.Max(0f, currentHealth - Mathf.Max(0f, amount));
UpdateHealthText();
if (currentHealth <= 0f)
{
Die();
return;
}
if (flashRoutine != null)
StopCoroutine(flashRoutine);
flashRoutine = StartCoroutine(FlashRoutine());
}
public void ResetTarget()
{
currentHealth = maxHealth;
if (targetCollider != null)
targetCollider.enabled = true;
if (targetRenderer != null)
targetRenderer.material.color = originalColor;
UpdateHealthText();
}
private void Die()
{
if (targetCollider != null)
targetCollider.enabled = false;
if (targetRenderer != null)
targetRenderer.material.color = Color.black;
UpdateHealthText();
}
private IEnumerator FlashRoutine()
{
if (targetRenderer != null)
targetRenderer.material.color = Color.yellow;
yield return new WaitForSeconds(0.08f);
if (targetRenderer != null && currentHealth > 0f)
targetRenderer.material.color = originalColor;
flashRoutine = null;
}
private void UpdateHealthText()
{
if (healthText != null)
healthText.text = "HP: " + Mathf.CeilToInt(currentHealth) + " / " + Mathf.CeilToInt(maxHealth);
}
}