56 lines
2.3 KiB
C#
56 lines
2.3 KiB
C#
using UnityEngine;
|
||
using UnityEngine.EventSystems;
|
||
using UnityEngine.UI;
|
||
|
||
/// <summary>
|
||
/// 点击音效组件:挂在 Button/Toggle 上,玩家点击时播放 tbaudio 表中的按钮音效(默认 60009 = PW_Button)。
|
||
/// ⭐ 由 UIBase 在面板显示时自动为所有子按钮补齐,无需手动挂载;列表项等运行时动态创建的按钮由面板兜底扫描补上。
|
||
/// 监听指针点击而不是 onClick/onValueChanged:代码里 isOn = true / SetIsOnWithoutNotify 等程序化改动不会误发音效,
|
||
/// 只在玩家真的点按时播放,同时与 Button/Toggle 自身的可交互规则保持一致。
|
||
/// </summary>
|
||
[DisallowMultipleComponent]
|
||
public class UIClickSound : MonoBehaviour, IPointerClickHandler
|
||
{
|
||
/// <summary>点击音效 ID(tbaudio 表;60009=PW_Button)。0=不播</summary>
|
||
public int clickAudioID = 60009;
|
||
|
||
public void OnPointerClick(PointerEventData eventData)
|
||
{
|
||
Play();
|
||
}
|
||
|
||
/// <summary>播放点击音效</summary>
|
||
public void Play()
|
||
{
|
||
if (clickAudioID <= 0) return;
|
||
|
||
// 与 Button/Toggle 自身规则一致:不可交互的不发声
|
||
var selectable = GetComponent<Selectable>();
|
||
if (selectable != null && !selectable.interactable) return;
|
||
|
||
if (AudioManager.Instance == null) return;
|
||
|
||
// 音效尚未加载(如启动早期默认音频未就绪)时静默跳过,避免连点刷错误日志
|
||
if (!AudioManager.Instance.HasClip(clickAudioID))
|
||
return;
|
||
|
||
AudioManager.Instance.PlayerFX(clickAudioID);
|
||
}
|
||
|
||
/// <summary>为 root 下所有 Button/Toggle 补齐点击音效(已有 UIClickSound 的跳过,可重复调用)</summary>
|
||
public static void AttachToAll(GameObject root, int audioID = 60009)
|
||
{
|
||
if (root == null || audioID <= 0) return;
|
||
foreach (var button in root.GetComponentsInChildren<Button>(true))
|
||
Attach(button, audioID);
|
||
foreach (var toggle in root.GetComponentsInChildren<Toggle>(true))
|
||
Attach(toggle, audioID);
|
||
}
|
||
|
||
private static void Attach(Selectable selectable, int audioID)
|
||
{
|
||
if (selectable.GetComponent<UIClickSound>() != null) return;
|
||
var sound = selectable.gameObject.AddComponent<UIClickSound>();
|
||
sound.clickAudioID = audioID;
|
||
}
|
||
} |