3 using System.Collections.Generic;
13 public static AudioSource ActiveSource
17 return _instance._sources[_instance._activeSourceIndex];
21 public static AudioSource IdleSource
25 int idleIndex = _instance._activeSourceIndex == 0 ? 1 : 0;
26 return _instance._sources[idleIndex];
30 public AnimationCurve FadeCurve;
32 AudioSource[] _sources;
33 int _activeSourceIndex;
38 _sources = GetComponents<AudioSource>();
39 _activeSourceIndex = 0;
42 public static void Play (
string trackName)
44 AudioClip track = Resources.Load<AudioClip>(trackName);
48 public static void Play (AudioClip track)
50 ActiveSource.loop =
true;
51 ActiveSource.clip = track;
52 ActiveSource.volume = 1;
56 public static void PlayOneShot (
string trackName)
58 AudioClip track = Resources.Load<AudioClip>(trackName);
67 ActiveSource.loop =
false;
68 ActiveSource.Play(track);
82 public static void CrossFade (
string trackName,
float fadeTime = 1.0f)
84 AudioClip track = Resources.Load<AudioClip>(trackName);
91 public static void CrossFade (AudioClip track,
float fadeTime = 1.0f)
93 _instance.StartCoroutine(_instance.CrossFadeAsync(track, fadeTime));
99 public static void FadeOut (
float fadeTime = 1.0f)
101 _instance.StartCoroutine(_instance.CrossFadeAsync(null, fadeTime));
106 _activeSourceIndex = _activeSourceIndex == 0 ? 1 : 0;
109 IEnumerator CrossFadeAsync (AudioClip incomingTrack,
float fadeTime)
111 IdleSource.clip = incomingTrack;
112 IdleSource.volume = 0;
114 if (IdleSource.clip != null)
117 for (
float t = 0; t < fadeTime; t += Time.deltaTime)
119 float s = t/fadeTime;
120 ActiveSource.volume = FadeCurve.Evaluate(1 - s);
121 IdleSource.volume = FadeCurve.Evaluate(s);
126 ActiveSource.loop =
true;
128 IdleSource.clip = null;
static void PlayOneShot(AudioClip track)
Abruptly play an audio track and don't loop it.
A Singleton Class that manages the music playing. Presists across scenes and provides various methods...
static void CrossFade(AudioClip track, float fadeTime=1.0f)
Given an audio clip, crossfade from the current track to it.
static void CrossFade(string trackName, float fadeTime=1.0f)
Given a string name of a music track, load that track and crossfade from the current track to it...
static void Stop()
Abruptly Stop playing the current audio track.
static void FadeOut(float fadeTime=1.0f)
Fade Out the currently playing track.