AudioCore0.1
This commit is contained in:
69
Assets/04.AudioCore/RunTime/SFXPlayer.cs
Normal file
69
Assets/04.AudioCore/RunTime/SFXPlayer.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user