I unfortunately hit a roadblock with this audio fading function I've made. It takes in a source, duration and a new clip. It is supposed to fade out the initial clip, replace the clip and lerp the volume back to 1.
public static IEnumerator FadeSwitchAudio(AudioSource audioSource, float duration, int clip)
{
float firstTimer = 0;
float secondTimer = 0;
float start = audioSource.volume;
// Fade audio out, works as intended
while (firstTimer < duration)
{
firstTimer += Time.deltaTime;
audioSource.volume = Mathf.Lerp(start, 0.01f, firstTimer / duration);
yield return null;
}
audioSource.clip = GameObject.FindWithTag("AudioManager").GetComponent<AudioManager>().clips[clip];
// Fade audio back in, volume jumps immediately to 1 and audiosource stops having output
yield return new WaitForSeconds(0.1f);
while (secondTimer < duration)
{
secondTimer += Time.deltaTime;
audioSource.volume = Mathf.Lerp(start, 1.0f, secondTimer / duration);
yield return null;
}
}
I have tried a lot of different timer functions, however, it seems that increasing the volume of an audiosource always breaks it. Is there a sure way to slowly increase the audio of a source without the source completely losing output? Here is a gif of the current behaviour in the inspector. Please excuse the low resolution but you can see the behaviour.
Thank you for your time!