72 lines
2.3 KiB
C#
72 lines
2.3 KiB
C#
using System.Collections;
|
||
using UnityEngine;
|
||
|
||
/// <summary>
|
||
/// UI 基类:统一生命周期、显示/隐藏、入场出场动画钩子、按钮点击音效
|
||
/// </summary>
|
||
public abstract class UIBase : MonoBehaviour
|
||
{
|
||
public UIPanel PanelType { get; private set; }
|
||
|
||
/// <summary>面板内按钮点击音效 ID(tbaudio 表;60009=PW_Button)。0=不播</summary>
|
||
public int buttonClickAudioID = 60009;
|
||
|
||
/// <summary>面板显示期间的点击音效兜底扫描协程</summary>
|
||
private Coroutine _clickSoundWatch;
|
||
|
||
// 初始化,由 UIManager 赋值
|
||
public void Init(UIPanel type)
|
||
{
|
||
PanelType = type;
|
||
OnInit();
|
||
}
|
||
|
||
// 生命周期钩子
|
||
protected virtual void OnInit() { }
|
||
protected virtual void OnShow(object args = null) { }
|
||
protected virtual void OnHide() { }
|
||
|
||
public virtual void Show(object args = null)
|
||
{
|
||
gameObject.SetActive(true);
|
||
transform.SetAsLastSibling(); // 每次激活都放到最上层
|
||
RefreshButtonClickSounds(); // ⭐ 先给面板内已有的按钮补齐点击音效
|
||
OnShow(args);
|
||
RefreshButtonClickSounds(); // ⭐ OnShow 中同步创建的按钮(如列表项)再补一遍
|
||
StartClickSoundWatch();
|
||
}
|
||
|
||
public virtual void Hide()
|
||
{
|
||
OnHide();
|
||
gameObject.SetActive(false);
|
||
}
|
||
|
||
/// <summary>给面板下所有 Button/Toggle 补齐点击音效(可重复调用,已挂 UIClickSound 的会跳过)</summary>
|
||
public void RefreshButtonClickSounds()
|
||
{
|
||
UIClickSound.AttachToAll(gameObject, buttonClickAudioID);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 面板显示期间每 0.3 秒兜底扫描一次:列表项等运行时动态创建的按钮也能自动带上点击音效
|
||
/// (已挂 UIClickSound 的会跳过,扫描开销很小)。面板隐藏后循环自动退出。
|
||
/// </summary>
|
||
private void StartClickSoundWatch()
|
||
{
|
||
if (_clickSoundWatch != null)
|
||
StopCoroutine(_clickSoundWatch);
|
||
_clickSoundWatch = StartCoroutine(ClickSoundWatchRoutine());
|
||
}
|
||
|
||
private IEnumerator ClickSoundWatchRoutine()
|
||
{
|
||
var wait = new WaitForSecondsRealtime(0.3f);
|
||
while (gameObject.activeInHierarchy)
|
||
{
|
||
yield return wait;
|
||
RefreshButtonClickSounds();
|
||
}
|
||
_clickSoundWatch = null;
|
||
}
|
||
} |