Un fade cambia el volumen gradualmente.
IEnumerator FadeOut(
AudioSource source,
float duracion)
{
float inicio = source.volume;
float tiempo = 0f;
while (tiempo < duracion)
{
tiempo += Time.unscaledDeltaTime;
source.volume = Mathf.Lerp(
inicio,
0f,
tiempo / duracion
);
yield return null;
}
source.volume = 0f;
}
IEnumerator FadeIn(
AudioSource source,
float duracion,
float volumenFinal)
{
source.volume = 0f;
source.Play();
float tiempo = 0f;
while (tiempo < duracion)
{
tiempo += Time.unscaledDeltaTime;
source.volume = Mathf.Lerp(
0f,
volumenFinal,
tiempo / duracion
);
yield return null;
}
source.volume = volumenFinal;
}
Permite que el fade siga funcionando incluso con:
Time.timeScale = 0f;
Mathf.Lerp(...)
Time.unscaledDeltaTime
StartCoroutine(...)