Skip to content

Instantly share code, notes, and snippets.

@dinukapj
Created January 21, 2022 07:34
Show Gist options
  • Save dinukapj/96c120c8f27696a1247e7e5a956bbfd8 to your computer and use it in GitHub Desktop.
Save dinukapj/96c120c8f27696a1247e7e5a956bbfd8 to your computer and use it in GitHub Desktop.
Fade out Unity Audio
public static class AudioFadeScript
{
public static IEnumerator FadeOut(AudioSource audioSource, float FadeTime)
{
float startVolume = audioSource.volume;
while (audioSource.volume > 0)
{
audioSource.volume -= startVolume * Time.deltaTime / FadeTime;
yield return null;
}
audioSource.Stop();
audioSource.volume = startVolume;
}
public static IEnumerator FadeIn(AudioSource audioSource, float FadeTime)
{
float startVolume = 0.2f;
audioSource.volume = 0;
audioSource.Play();
while (audioSource.volume < 1.0f)
{
audioSource.volume += startVolume * Time.deltaTime / FadeTime;
yield return null;
}
audioSource.volume = 1f;
}
}
//use this to call these methods
// stop menu music
StartCoroutine(AudioFadeScript.FadeOut(audioMenuMusic, 0.5f));
// start game music
StartCoroutine(AudioFadeScript.FadeIn(audioGameMusic, 5f));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment