Files
bansonic_beta_main/Assets/UIFrameWork/UISoundRouter.cs
T

117 lines
3.3 KiB
C#

using UnityEngine;
using System.Collections.Generic;
public class UISoundRouter : MonoBehaviour
{
public static UISoundRouter Instance;
[SerializeField] private UISoundConfig soundConfig;
private Dictionary<UIButtonType, UISoundConfig.ButtonSoundEntry> lookup;
private AudioSource audioSource;
private float lastHoverTime;
private float hoverCooldown = 0.1f;
private float lastClickTime;
private float clickCooldown = 0.1f;
void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
// 限制最大并发声音数量,防止音频叠加导致的音量过大
audioSource.priority = 128;
BuildLookup();
}
public void SetConfig(UISoundConfig config)
{
soundConfig = config;
if (soundConfig != null && audioSource != null)
{
audioSource.outputAudioMixerGroup = soundConfig.outputGroup;
}
BuildLookup();
}
void BuildLookup()
{
lookup = new Dictionary<UIButtonType, UISoundConfig.ButtonSoundEntry>();
if (soundConfig == null)
{
Debug.LogWarning("[UISoundRouter] SoundConfig is null! Cannot build lookup.");
return;
}
Debug.Log($"[UISoundRouter] Building lookup for {soundConfig.name} with {soundConfig.soundTable.Count} entries.");
foreach (var entry in soundConfig.soundTable)
{
lookup[entry.type] = entry;
Debug.Log($"[UISoundRouter] Registered sound for {entry.type}: Hover={entry.hoverClip?.name}, Click={entry.clickClip?.name}");
}
}
public void PlayHover(UIButtonType type)
{
if (Time.unscaledTime - lastHoverTime < hoverCooldown)
return;
lastHoverTime = Time.unscaledTime;
if (lookup != null && lookup.TryGetValue(type, out var entry))
{
if (entry.hoverClip != null)
{
// 使用较小的音量播放悬停音效,减少叠加感
audioSource.PlayOneShot(entry.hoverClip, 0.7f);
}
else
{
Debug.LogWarning($"[UISoundRouter] Hover clip is null for type {type}");
}
}
else
{
Debug.LogWarning($"[UISoundRouter] No entry found for type {type} in lookup.");
}
}
public void PlayClick(UIButtonType type)
{
if (Time.unscaledTime - lastClickTime < clickCooldown)
return;
lastClickTime = Time.unscaledTime;
Debug.Log($"[UISoundRouter] PlayClick called for type: {type}");
if (lookup != null && lookup.TryGetValue(type, out var entry))
{
if (entry.clickClip != null)
{
Debug.Log($"[UISoundRouter] Playing click clip: {entry.clickClip.name}");
audioSource.PlayOneShot(entry.clickClip, 1.0f);
}
else
{
Debug.LogWarning($"[UISoundRouter] Click clip is null for type {type}");
}
}
else
{
Debug.LogWarning($"[UISoundRouter] No entry found for type {type} in lookup.");
}
}
}