69 lines
1.8 KiB
C#
69 lines
1.8 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class SFXPlayer
|
|
{
|
|
private AudioSourcePool audioSourcePool;
|
|
private List<AudioSource> activeSources = new List<AudioSource>(); // 正在播放的 AudioSource 列表
|
|
|
|
public SFXPlayer(AudioSourcePool audioSourcePool)
|
|
{
|
|
this.audioSourcePool = audioSourcePool;
|
|
}
|
|
|
|
/*public override void Play(AudioClip clip, float volume = 1f)
|
|
{
|
|
AudioSource source = audioSourcePool.GetAudioSource("SFX");
|
|
if (source == null) return;
|
|
|
|
source.clip = clip;
|
|
source.volume = volume;
|
|
source.Play();
|
|
|
|
// 将 AudioSource 加入活动列表
|
|
activeSources.Add(source);
|
|
}
|
|
*/
|
|
|
|
// 播放音效
|
|
public void Play(AudioClip clip, float volume = 1f, System.Action onComplete = null, float delay = 0f)
|
|
{
|
|
AudioSource source = audioSourcePool.GetAudioSource("SFX");
|
|
if (source == null) return;
|
|
|
|
source.clip = clip;
|
|
source.volume = volume;
|
|
source.Play();
|
|
|
|
// 将 AudioSource 加入活动列表
|
|
activeSources.Add(source);
|
|
|
|
// 使用协程处理延迟和回调
|
|
CoroutineHelper.StartCoroutine(PlayCoroutine(source, delay, onComplete));
|
|
}
|
|
|
|
// 停止所有音效
|
|
public void Stop()
|
|
{
|
|
foreach (var source in activeSources)
|
|
{
|
|
if (source.isPlaying)
|
|
{
|
|
source.Stop();
|
|
audioSourcePool.ReturnAudioSource("SFX", source.gameObject);
|
|
}
|
|
}
|
|
activeSources.Clear();
|
|
}
|
|
|
|
// 播放音效的协程
|
|
private IEnumerator PlayCoroutine(AudioSource source, float delay, System.Action onComplete)
|
|
{
|
|
yield return new WaitForSeconds(source.clip.length + delay);
|
|
|
|
onComplete?.Invoke();
|
|
audioSourcePool.ReturnAudioSource("SFX", source.gameObject);
|
|
activeSources.Remove(source);
|
|
}
|
|
} |