using System.Collections; using System.Collections.Generic; using UnityEngine; public class MusicFadeController : MonoBehaviour { [SerializeField] public AudioSource audioSource; public bool shouldLoop = false; public float originalVolume = 1; // Keeps track of the most recent fade command. // Previous fades should stop as soon as the actionCounter increments. public int actionCounter = 0; // Credit: https://forum.unity.com/threads/fade-out-audio-source.335031/ public IEnumerator IFadeIn(float time) { int cache = ++actionCounter; audioSource.volume = 0; while (audioSource.volume < originalVolume && actionCounter == cache) { audioSource.volume += originalVolume * Time.deltaTime / time; yield return null; } // Skip if preempted if (cache != actionCounter) yield break; audioSource.volume = originalVolume; } // Credit: https://forum.unity.com/threads/fade-out-audio-source.335031/ IEnumerator IFadeOut(float time) { int cache = ++actionCounter; audioSource.volume = originalVolume; while (audioSource.volume > 0 && actionCounter == cache) { audioSource.volume -= originalVolume * Time.deltaTime / time; yield return null; } // Skip if preempted if (cache != actionCounter) yield break; audioSource.Stop(); shouldLoop = false; audioSource.volume = originalVolume; } IEnumerator IFadeOutThenIn(float outTime, float inTime, AudioClip loopClip) { int cache = ++actionCounter; if (audioSource.isPlaying) { audioSource.volume = originalVolume; while (audioSource.volume > 0 && actionCounter == cache) { audioSource.volume -= originalVolume * Time.deltaTime / outTime; yield return null; } // Skip if preempted if (cache != actionCounter) yield break; audioSource.Stop(); } audioSource.volume = 0; audioSource.clip = loopClip; audioSource.Play(); while (audioSource.volume < originalVolume && actionCounter == cache) { audioSource.volume += originalVolume * Time.deltaTime / inTime; yield return null; } // Skip if preempted if (cache != actionCounter) yield break; audioSource.volume = originalVolume; } public void ChangeVolume(float volume) { audioSource.volume = originalVolume = volume; } public void FadeIn(float time) { StartCoroutine(IFadeIn(time)); } public void FadeOut(float time) { StartCoroutine(IFadeOut(time)); } public void FadeOutThenIn(float o, float i, AudioClip loopClip) { StartCoroutine(IFadeOutThenIn(o, i, loopClip)); } IEnumerator PlayLoopAfter(float time, AudioClip loopClip) { yield return new WaitForSeconds(time); if (shouldLoop) { audioSource.clip = loopClip; audioSource.Play(); } } public void PlayMainMenuLoopAfter(float time, AudioClip loopClip) { StartCoroutine(PlayLoopAfter(time, loopClip)); } // Start is called before the first frame update void Start() { originalVolume = audioSource.volume; } // Update is called once per frame void Update() { } }