- Home /
Continuous AudioSource in DontDestroyOnLoad
My game contains multiple scenes and I want play continuous game music between multiple scenes.
For this purpose, I have written code like this:
public static SoundManager Instance { get { return instance; } }
public AudioClip[] levelClips;
public AudioSource bgMusicAS;
//
private static SoundManager instance;
private bool isSoundEnable;
private void Awake ()
{
if (SoundManager.Instance != null) {
Destroy (gameObject);
return;
}
DontDestroyOnLoad (gameObject);
instance = this;
isSoundEnable = DataStorage.RetrieveSoundStatus ();
}
At main menu of game, above code script get executed and Don'tDestroyOnLoad AudioSource gameobject get created. But when I move ahead into game play scene, game music started from first, now from where we left in main menu scene.
I want this to be continuous between all scenes of game. Please give me some suggestion for this.
EDIT:
This is the way how I play and pause background music.
public void PlayLevelMusic (int musicId)
{
if (!isSoundEnable)
return;
bgMusicAS.clip = levelClips [musicId];
bgMusicAS.Play ();
}
public void StopLevelMusic ()
{
bgMusicAS.Pause ();
}
At new scene start, automatically background music get started from first in all scenes I have.
The code in general seems to be correct (UPDATE: and I've just tested it, it works). How do you play the AudioClip
s? Could it be that you unintentionally start playing from the beginning when you load a new scene?
@Harinezumi I have updated my question with more details...
Answer by Harinezumi · Jun 04, 2018 at 03:14 PM
The problem is that AudioSource.Play()
resets the progress of the AudioClip
. When you call PlayLevelMusic()
check that the selected clip is different from the currently played clip, and only change and start playing if they are. Like this:
if (bgMusicAS.clip != levelClips[musicId]) {
bgMusicAS.clip = levelClips[musicId];
bgMusicAS.Play();
}
Last 1 week problem get solved, thank you for your quick help :)
Your answer
Follow this Question
Related Questions
Unity 2d select 2 object on another 2 scenes 2 Answers
Working between different scenes! 1 Answer
DontDestroyOnLoad problem 1 Answer