using System.Collections; using System.Collections.Generic; using UnityEngine; public class SFXPlayer { private AudioSourcePool audioSourcePool; private List activeSources = new List(); // 正在播放的 AudioSource 列表 public SFXPlayer(AudioSourcePool audioSourcePool) { this.audioSourcePool = audioSourcePool; } /// /// 播放音效 /// /// 音频 /// 音量 /// 结束行为 /// 延迟结束行为时间 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(PlaySFXCoroutine(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 PlaySFXCoroutine(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); } }