using UnityEngine; // 敵人血條 : 裡面那條會依剩餘血量縮短,左邊固定、從右邊往左扣 public class EnemyHealthBar : MonoBehaviour { [Header("參照")] public BotSpawner spawner; [Tooltip("整個血條 (外框),沒有敵人時隱藏")] public GameObject panel; [Tooltip("會縮短的那條 (外框裡面的 Image)")] public RectTransform fill; private float fullWidth; private float centerX; private float shownRatio = -1f; void Start() { // 沒拖、或拖到 prefab 檔案本身 : 自動找場景裡的 BotSpawner (新地圖不用再手動接) spawner = BotSpawner.FindInScene(spawner); } void Awake() { if (fill != null) { fullWidth = fill.sizeDelta.x; centerX = fill.anchoredPosition.x; } } void Update() { // 機器人倒下到重生之間先隱藏 BotHealth bot = spawner != null ? spawner.CurrentBot : null; if (panel != null) panel.SetActive(bot != null); if (bot == null || fill == null) return; float ratio = bot.maxHealth > 0f ? Mathf.Clamp01(bot.Health / bot.maxHealth) : 0f; if (Mathf.Approximately(ratio, shownRatio)) return; shownRatio = ratio; // 寬度照比例縮短,再依 Pivot 往左移,讓左邊維持在原位 float width = fullWidth * ratio; fill.sizeDelta = new Vector2(width, fill.sizeDelta.y); fill.anchoredPosition = new Vector2(centerX - fill.pivot.x * (fullWidth - width), fill.anchoredPosition.y); } }