using UnityEngine; using TMPro; using System.Collections; using Yarn.Unity; public class MessageBox : MonoBehaviour { public static MessageBox Instance { get; private set; } public TMP_Text state; // 显示状态的TextMeshPro组件 public TMP_Text text; // 显示消息的TextMeshPro组件 private void Awake() { // 确保单例模式 if (Instance != null && Instance != this) { Destroy(gameObject); } else { Instance = this; DontDestroyOnLoad(gameObject); // 可选:保持在场景加载之间 } } // Yarn Command处理方法 [YarnCommand("messagebox")] public void HandleMessageBoxCommand(string type, string message) { switch (type.ToLower()) { case "warning": SetWarning(message); break; case "normal": SetNormal(message); break; case "null": SetNull(); break; default: Debug.LogError("Invalid message type for messagebox command: " + type); break; } } private void Start() { SetNull(); } // 设置为Warning状态 private void SetWarning(string message) { state.text = "WARNING"; state.color = Color.red; // 红色 text.text = message; text.color = Color.white; // 默认文本颜色 StartCoroutine(FlashWarning()); // 开始闪烁效果 } // 设置为Normal状态 private void SetNormal(string message) { state.text = "NORMAL"; state.color = new Color(1.0f, 0.55f, 0.0f); // 琥珀色 text.text = message; text.color = Color.white; // 默认文本颜色 StopCoroutine(FlashWarning()); // 停止闪烁效果(如果正在闪烁) } // 设置为Null状态 public void SetNull() { state.text = "NO SIGNAL"; state.color = Color.blue; // 蓝色 text.text = string.Empty; text.color = Color.white; // 默认文本颜色 StopCoroutine(FlashWarning()); // 停止闪烁效果(如果正在闪烁) } // 闪烁警告效果 private IEnumerator FlashWarning() { for (int i = 0; i < 3; i++) { state.enabled = false; yield return new WaitForSeconds(0.5f); // 闪烁间隔 state.enabled = true; yield return new WaitForSeconds(0.5f); // 闪烁间隔 } state.enabled = true; // 确保闪烁后状态仍然可见 } }