Continuous AudioSource in DontDestroyOnLoad GameObject

450 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

I have found the solution for this problem through the help of @Harinezumi in Unity Question/Answer section.

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();
 }
1
On

As a solution you can use SceneManager.LoadSceneAsync() and place your music object in a seperate scene.

DontDestroyOnLoad is likely to get depreciated in the future anyways (although do not quote me on this I have no inside info this is guesswork)