- Home /
Audio from scene 1 & 2 continues to play in scene 3 even though it was not added to scene 3.
Hi guys. I used the code below to get the solve the problem of the same song that is playing in scene 1 starting to play from the beginning in scene 2, instead of seamlessly continuing the song when I switch scenes. The song plays in all my menu scenes, regardless of my switching between scenes. But when I switch into the scene that has actual game play, the menu song plays alongside the game play song. The unity console warns that I have 2 audio listeners in my scene, even though I didn't add the audio game object from the menu scenes to the scene that has game play. The script is attached to empty game objects (with an audio listener and an audio source) in the menu scenes, but such a "MenuAudioGameObject" does not exist in the game play scene. Any clue on what I can do?
public class MenuAudio : MonoBehaviour { private static MenuAudio instance;
void Awake()
{
if (instance != null && instance != this)
{
Destroy (this.gameObject);
return;
}
else
instance = this;
DontDestroyOnLoad (this.gameObject);
}
// Use this for initialization
void Start ()
{
if (!instance.audio.isPlaying)
audio.Play ();
}
public void TurnMusicOff ()
{
if (instance != null)
{
Destroy(this.gameObject);
instance = null;
}
}
void OnApplicationQuit()
{
instance = null;
}
}
Answer by yashpal · Jan 30, 2015 at 09:20 AM
@Tolufoyeh, basically you have two problems (1) you get the warning "you have 2 audio listeners in scene." and (2) music play in all the scenes.
In every scene camera have audio listener and your audio gameObject "MenuAudioGameObject" also have audio listener. so unity show warning "you have 2 audio listeners in scene.". this happens because your "MenuAudioGameObject" don't destroy in between scene.
so when you change the menuScene to gamePlayScene you turn off your audio Listener of "MenuAudioGameObject" and pause audioSource.
Thanks! I just had to change the first line of the above code from private static $$anonymous$$enuAudio instance; to public static $$anonymous$$enuAudio instance; so I could call add this line to the start method of my GamePlayScene: $$anonymous$$enuAudio.instance.Turn$$anonymous$$usicOff (); and it works perfectly now. I thought the music might not resume when I switched from gameplay back to menu scenes but it all works like it should now.
How do I mark the thread as solved? Or is that the job of the ad$$anonymous$$s?