45 lines
1.4 KiB
C#
45 lines
1.4 KiB
C#
using UnityEngine;
|
||
using BaseGames.Core;
|
||
|
||
namespace BaseGames.Audio
|
||
{
|
||
/// <summary>
|
||
/// 全局 SFX 播放入口(单例 MonoBehaviour)。
|
||
/// 通过 <see cref="Play"/> 静态方法播放 <see cref="AudioEventSO"/>,
|
||
/// 可选传入世界坐标以在指定位置 3D 播放。
|
||
/// </summary>
|
||
public class GlobalSFXPlayer : MonoBehaviour
|
||
{
|
||
private static GlobalSFXPlayer _instance;
|
||
|
||
[SerializeField] private AudioSource _globalSFXSource;
|
||
|
||
private void Awake()
|
||
{
|
||
if (_instance != null) { Destroy(gameObject); return; }
|
||
_instance = this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 播放一个音效事件。
|
||
/// <para>若传入 <paramref name="worldPos"/>,则在该位置 3D 播放;否则使用全局 AudioSource 2D 播放。</para>
|
||
/// </summary>
|
||
public static void Play(AudioEventSO audioEvent, Vector2? worldPos = null)
|
||
{
|
||
if (audioEvent == null || _instance == null) return;
|
||
|
||
if (worldPos.HasValue)
|
||
{
|
||
var clip = audioEvent.PickClip();
|
||
if (clip != null)
|
||
ServiceLocator.GetOrDefault<IAudioService>()
|
||
?.PlaySFXAtPosition(clip, worldPos.Value, audioEvent.PickVolume());
|
||
}
|
||
else
|
||
{
|
||
audioEvent.Play(_instance._globalSFXSource);
|
||
}
|
||
}
|
||
}
|
||
}
|