Hi People,
I am trying to get my game to fade in music when a scene loads.
I have an Audio Manager singleton that is being retained through scene loads. However I am having issues with the fading in working correctly. The FadeOut before the scene load works fine but the FadeIn has some odd issues.
I call the below IEmumerator from a function in the AudioManager.
public IEnumerator IFadeIn(string _name, float _targetVolume, float _duration)
{
Music m = musics.Find(music => music.name == _name);
if (m == null)
{
Debug.LogError("Music name" + _name + "not found!");
yield return null;
}
else
{
if (fadeIn == false)
{
fadeIn = true;
instance.fadeInUsedString = _name;
m.source.volume = 0f;
m.source.Play();
Debug.Log("Playing: " + _name);
while (m.source.volume < _targetVolume)
{
m.source.volume += Time.deltaTime / _duration;
yield return null;
}
yield return new WaitForSeconds(_duration);
fadeIn = false;
}
else
{
Debug.Log("Unable to fade In 2 music tracks at the same time!");
StopMusic(fadeInUsedString);
PlayMusic(_name);
}
}
}
The above is the FadeIn IEnumerator which should smoothly fade in the music from 0f Volume to the desired volume.
I am using this in my GameController script on the triggering of the SceneManager.SceneLoaded as below
private void Start()
{
sceneChanged = true;
player = Player.PlayerInstance;
gameOver = Resources.FindObjectsOfTypeAll<GameObject>().FirstOrDefault(g => g.name == "GameOverUI");
pauseUI = Resources.FindObjectsOfTypeAll<GameObject>().FirstOrDefault(g => g.name == "PauseUI");
}
private void Update()
{
SceneManager.sceneLoaded += startScene;
if (sceneChanged)
{
AudioManager.FadeIn(SceneManager.GetActiveScene().name, 0.35f, 2f);
sceneChanged = false;
}
}
public void startScene(Scene scene, LoadSceneMode mode)
{
sceneChanged = true;
gameOver.SetActive(false);
PlayerReset();
}
The issue is that the music does start and fade but it starts at a volume higher than 0 and then almosts jumps up to the desire volume.
Is this because I am calling a standard function from the update? Does it need to be an IEnumerator?
If anyone can help as I have been trying to fix it to no avail
Thanks
James