using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace AibisDream.UI { [RequireComponent(typeof(SpriteProgressBar))] public class SignLightHandler : MonoBehaviour { [Header("颜色设置")] [SerializeField] private Color lessColor; [SerializeField] private Color nearColor; [SerializeField] private Color moreColor; [Header("引用")] [SerializeField] private SpriteProgressBar progressBar; [SerializeField] private SpriteRenderer signLight; private void OnEnable() { if (progressBar != null) { // 订阅进度条的值变化事件 progressBar.OnValueChanged.AddListener(OnProgressBarValueChanged); } } private void OnDisable() { if (progressBar != null) { // 取消订阅 progressBar.OnValueChanged.RemoveListener(OnProgressBarValueChanged); } } private void OnProgressBarValueChanged(int currentValue) { if (progressBar == null) return; // 获取 SpriteRenderer 列表并更新颜色 var renderers = progressBar.SpriteRenderers; var maxValue = progressBar.MaxValue; UpdateColors(currentValue, maxValue, renderers); // 更新信号灯 UpdateSignLight(currentValue, maxValue); } /// /// 更新颜色逻辑 /// 根据 currentValue 和 maxValue 更新 renderers 列表中每个 SpriteRenderer 的颜色 /// /// 当前值 /// 最大值 /// SpriteRenderer 列表 private void UpdateColors(int currentValue, int maxValue, IReadOnlyList renderers) { Color targetColor; // 如果当前值小于最大值的5%,则设置为lessColor if (currentValue < maxValue * 0.95f) { targetColor = lessColor; } // 如果当前值大于最大值,则设置为moreColor else if (currentValue >= maxValue) { targetColor = moreColor; } // 如果当前值大于最大值的5%,则设置为nearColor else { targetColor = nearColor; } foreach (var renderer in renderers) { renderer.color = targetColor; } } private void UpdateSignLight(int currentValue, int maxValue) { Color targetColor; // 如果当前值小于最大值的5%,则设置为lessColor if (currentValue < maxValue * 0.95f) { targetColor = lessColor; } // 如果当前值大于最大值,则设置为moreColor else if (currentValue >= maxValue) { targetColor = moreColor; } // 如果当前值大于最大值的5%,则设置为nearColor else { targetColor = nearColor; } signLight.color = targetColor; } #if UNITY_EDITOR private void OnValidate() { // 如果进度条引用为空,尝试自动查找 if (progressBar == null) { progressBar = GetComponent(); if (progressBar == null) { progressBar = GetComponentInParent(); } } // 在编辑器中预览颜色变化 if (!Application.isPlaying && progressBar != null) { // 延迟执行,避免在序列化过程中出现问题 EditorApplication.delayCall += OnEditorPreview; } } private void OnEditorPreview() { if (this == null || gameObject == null) return; EditorApplication.delayCall -= OnEditorPreview; if (!Application.isPlaying && progressBar != null) { var renderers = progressBar.SpriteRenderers; if (renderers != null && renderers.Count > 0) { UpdateColors(progressBar.CurrentValue, progressBar.MaxValue, renderers); } } } #endif } }