DCS/ruiyiweiUX/Assets/Scripts/UI/AlarmLightComponent.cs

142 lines
3.8 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
/// <summary>
/// 报警灯组件,支持不同优先级的闪烁模式
/// </summary>
public class AlarmLightComponent : MonoBehaviour
{
[Header("报警灯设置")]
// public Image alarmLight;
public TextMeshProUGUI AlarmInfoText;
public Color highPriorityColor = Color.red;
public Color mediumPriorityColor = Color.yellow;
public Color lowPriorityColor = Color.yellow;
public Color normalColor = Color.gray;
public Color healthyColor = Color.green; // ✅ 健康状态颜色(绿色)
[Header("闪烁设置")]
public float blinkInterval = 0.5f; // 500ms闪烁周期
private AlarmPriority currentPriority = AlarmPriority.None;
private bool isBlinking = false;
private Coroutine blinkCoroutine;
void Awake()
{
// if (alarmLight == null)
// alarmLight = GetComponent<Image>();
ResetLight();
DCSAlarmManager.OnAlarmCleared += OnAllAlarmsCleared;
}
/// <summary>
/// 设置报警状态
/// </summary>
public void SetAlarmState(AlarmPriority priority, bool isActive)
{
if (blinkCoroutine != null)
{
StopCoroutine(blinkCoroutine);
blinkCoroutine = null;
}
currentPriority = priority;
isBlinking = isActive;
if (!isActive)
{
ResetLight();
return;
}
switch (priority)
{
case AlarmPriority.High:
// 高优先级:红灯闪烁
blinkCoroutine = StartCoroutine(BlinkLight(highPriorityColor));
break;
case AlarmPriority.Medium:
// 中优先级:黄灯闪烁
blinkCoroutine = StartCoroutine(BlinkLight(mediumPriorityColor));
break;
case AlarmPriority.Low:
// 低优先级:黄灯常亮
// alarmLight.color = lowPriorityColor;
AlarmInfoText.color = lowPriorityColor;
break;
default:
ResetLight();
break;
}
}
private void OnAllAlarmsCleared()
{
if (blinkCoroutine != null)
{
StopCoroutine(blinkCoroutine);
blinkCoroutine = null;
}
isBlinking = false;
currentPriority = AlarmPriority.None;
if (AlarmInfoText != null)
{
// alarmLight.color = healthyColor; // ✅ 显示绿色健康状态
AlarmInfoText.color = healthyColor;
}
Debug.Log("[报警灯] 切换到健康状态(绿色)");
}
/// <summary>
/// 闪烁协程
/// </summary>
private IEnumerator BlinkLight(Color color)
{
while (isBlinking)
{
// alarmLight.color = color;
AlarmInfoText.color = color;
yield return new WaitForSeconds(blinkInterval);
// alarmLight.color = normalColor;
AlarmInfoText.color = normalColor;
yield return new WaitForSeconds(blinkInterval);
}
}
/// <summary>
/// 重置灯光状态
/// </summary>
private void ResetLight()
{
// if (alarmLight != null)
// alarmLight.color = normalColor;
if (AlarmInfoText != null)
AlarmInfoText.color = normalColor;
isBlinking = false;
currentPriority = AlarmPriority.None;
}
void OnDestroy()
{
if (blinkCoroutine != null)
{
StopCoroutine(blinkCoroutine);
}
DCSAlarmManager.OnAlarmCleared -= OnAllAlarmsCleared;
}
}