Files
gold_dolphin/unity/Assets/UI/UIClickSoundHandler.cs
2026-07-04 18:35:23 +08:00

47 lines
1.6 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace GameFramework
{
/// <summary>
/// 全局 UI 按钮音效处理器。
/// 挂到 Canvas 上,自动监听所有按钮的点击/悬停事件并播放音效。
/// 无需在每个按钮上单独添加组件。
/// </summary>
public class UIClickSoundHandler : MonoBehaviour, IPointerEnterHandler, IPointerDownHandler
{
[Header("音效资源路径(相对于 Resources 文件夹)")]
[SerializeField] private string selectSFXPath = "SFX/UI_Click";
[SerializeField] private string clickSFXPath = "SFX/UI_Click";
[Header("音量")]
[SerializeField] private float selectVolume = 0.5f;
[SerializeField] private float clickVolume = 0.6f;
private void PlaySFX(string path, float volume)
{
if (AudioManager.Instance != null)
AudioManager.Instance.PlaySFXFromResources(path, volume);
}
public void OnPointerEnter(PointerEventData eventData)
{
// 只对按钮播放悬停音效
if (eventData.pointerEnter != null && eventData.pointerEnter.GetComponent<Button>() != null)
{
PlaySFX(selectSFXPath, selectVolume);
}
}
public void OnPointerDown(PointerEventData eventData)
{
// 只对按钮播放点击音效
if (eventData.pointerPress != null && eventData.pointerPress.GetComponent<Button>() != null)
{
PlaySFX(clickSFXPath, clickVolume);
}
}
}
}