Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public static class AudioClipExtention
- {
- static List<PooledAudioSource> sourcesPool = new List<PooledAudioSource>();
- public static int totalNumberOfAudioSources;
- public static Transform parent;
- public static int maxSourcesCount = 32;
- public static void PlayWithSource(this AudioClip aClip, object caller)
- {
- PooledAudioSource p = ReturnSource();
- if (p == null) { Debug.LogWarning("Could not play the clip: " + aClip.name + " because there are more than " + maxSourcesCount + " sources in the scene."); return; }
- p.Play( caller, aClip);
- }
- public static void PlayWithSource(this AudioClip aClip, object caller, float volume, float pitch)
- {
- PooledAudioSource p = ReturnSource();
- if (p == null) { Debug.LogWarning("Could not play the clip: " + aClip.name + " because there are more than " + maxSourcesCount + " sources in the scene."); return; }
- p.Play(caller, aClip, volume, pitch);
- }
- public static void SourceFinishedPlaying(PooledAudioSource ps)
- {
- sourcesPool.Add(ps);
- }
- static PooledAudioSource ReturnSource()
- {
- if(sourcesPool.Count >0)
- {
- PooledAudioSource toReturn = sourcesPool[sourcesPool.Count - 1];
- sourcesPool.RemoveAt(sourcesPool.Count - 1);
- return toReturn;
- }
- if (totalNumberOfAudioSources >= maxSourcesCount) return null;
- return new PooledAudioSource();
- }
- }
- public class PooledAudioSource
- {
- AudioSource source;
- public PooledAudioSource()
- {
- if(source == null)
- {
- source = new GameObject().AddComponent<AudioSource>();
- AudioClipExtention.totalNumberOfAudioSources++;
- source.gameObject.name = "Pooled_AudioSources_" + AudioClipExtention.totalNumberOfAudioSources;
- if (AudioClipExtention.parent == null) AudioClipExtention.parent = new GameObject("PooledAudios").transform;
- source.gameObject.transform.parent = AudioClipExtention.parent;
- source.playOnAwake = false;
- source.loop = false;
- }
- }
- public void Play(object caller, AudioClip c)
- {
- source.enabled = true;
- source.clip = c;
- source.Play();
- ((MonoBehaviour)caller).StartCoroutine(TrackProgress(c.length));
- }
- public void Play(object caller, AudioClip c, float volume, float pitch)
- {
- source.enabled = true;
- source.clip = c;
- source.volume = volume;
- source.pitch = pitch;
- source.Play();
- ((MonoBehaviour)caller).StartCoroutine(TrackProgress(c.length));
- }
- IEnumerator TrackProgress(float length)
- {
- yield return new WaitForSeconds(length+0.1f);
- FinishedPlaying();
- }
- void FinishedPlaying()
- {
- source.clip = null;
- source.enabled = false;
- AudioClipExtention.SourceFinishedPlaying(this);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement