0

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.

4

2 回答 2

0

作为一种解决方案,您可以使用 SceneManager.LoadSceneAsync() 并将您的音乐对象放在单独的场景中。

无论如何,DontDestroyOnLoad 将来很可能会贬值(尽管不要引用我的话,我没有内部信息,这是猜测)

于 2018-06-04T13:38:22.983 回答
0

我在 Unity Question/Answer 部分通过@Harinezumi 的帮助找到了解决这个问题的方法。

问题是 AudioSource.Play() 重置了 AudioClip 的进度。当您调用 PlayLevelMusic() 时,检查所选剪辑是否与当前播放的剪辑不同,并且只有在它们不同时才更改并开始播放。像这样:

if (bgMusicAS.clip != levelClips[musicId]) {
     bgMusicAS.clip = levelClips[musicId];
     bgMusicAS.Play();
 }
于 2018-06-04T18:05:50.640 回答