Created
January 21, 2022 07:34
-
-
Save dinukapj/96c120c8f27696a1247e7e5a956bbfd8 to your computer and use it in GitHub Desktop.
Fade out Unity Audio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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