MiniGames/Assets/Scripts/CrateEscape/LaserBoxHealth.cs
2025-08-19 16:59:43 +05:00

99 lines
2.7 KiB
C#

using UnityEngine;
using System.Collections.Generic;
public class LaserBoxHealth : MonoBehaviour
{
[Header("Health Settings")]
public float maxHealth = 100f;
public float currentHealth = 100f;
public float damagePerHit = 10f;
[Header("Visual Feedback")]
public Renderer targetRenderer; // assign your MeshRenderer here if not on same object
private List<Material> runtimeMaterials = new List<Material>();
private List<Color> originalColors = new List<Color>();
[Header("Destruction")]
public float destructionDuration = 1f;
private bool isDestroying = false;
void Start()
{
if (!targetRenderer)
targetRenderer = GetComponent<Renderer>();
if (targetRenderer != null)
{
var sharedMats = targetRenderer.materials;
runtimeMaterials.Clear();
originalColors.Clear();
for (int i = 0; i < sharedMats.Length; i++)
{
Material mat = new Material(sharedMats[i]); // create runtime copy
runtimeMaterials.Add(mat);
originalColors.Add(mat.color);
}
targetRenderer.materials = runtimeMaterials.ToArray(); // assign runtime copies
}
currentHealth = maxHealth;
}
public void TakeLaserDamage()
{
if (isDestroying || currentHealth <= 0f) return;
currentHealth -= damagePerHit;
currentHealth = Mathf.Clamp(currentHealth, 0f, maxHealth);
UpdateColors();
if (currentHealth <= 0f)
{
StartCoroutine(ScaleAndDisable());
}
}
void UpdateColors()
{
float healthPercent = currentHealth / maxHealth;
for (int i = 0; i < runtimeMaterials.Count; i++)
{
if (runtimeMaterials[i] == null) continue;
Color targetColor = originalColors[i];
if (healthPercent <= 0.5f && healthPercent > 0.1f)
{
float t = Mathf.InverseLerp(0.5f, 0.1f, healthPercent);
runtimeMaterials[i].color = Color.Lerp(Color.black, targetColor, t);
}
else if (healthPercent <= 0.1f)
{
runtimeMaterials[i].color = Color.black;
}
}
}
System.Collections.IEnumerator ScaleAndDisable()
{
isDestroying = true;
Vector3 startScale = transform.localScale;
Vector3 endScale = Vector3.zero;
float t = 0f;
while (t < destructionDuration)
{
t += Time.deltaTime;
transform.localScale = Vector3.Lerp(startScale, endScale, t / destructionDuration);
yield return null;
}
gameObject.SetActive(false);
}
}