- Home /
Audio and Scene Switching
I have been working on this for a while now and cannot figure it out! This cannot be that difficult and I may be overlooking something very simple. When I start the game the audio plays fine and stops when I go into gameplay, but if I quit from the gameplay scene and go back to the main menu the audio does not play. Why would this be happening?
Here's my code:
using UnityEngine;
using System.Collections;
using UnityEngine .SceneManagement ;
public class AudioManager : MonoBehaviour {
public AudioSource BGM;
static bool AudioBegin = false;
// Use this for initialization
void Awake () {
}
void Start(){
if (AudioBegin == false) {
BGM.Play ();
DontDestroyOnLoad (gameObject);
AudioBegin = true;
}
/*if (FindObjectsOfType <AudioManager > ().Length>1) {
Destroy (gameObject);
}*/
}
// Update is called once per frame
void Update () {
if ((SceneManager.GetActiveScene ().name == "Title Menu" && AudioBegin == false)){
BGM.Play ();
DontDestroyOnLoad (gameObject);
AudioBegin = true;
}
if ((SceneManager.GetActiveScene ().name=="Gameplay") && AudioBegin == true) {
BGM.Stop ();
DontDestroyOnLoad (gameObject);
AudioBegin = false;
}
if (FindObjectsOfType <AudioManager > ().Length>1) {
Destroy (gameObject);
}
}
}
Aren't you destroying the Audio$$anonymous$$anager in the last if of your Update function?
Answer by eirikamb · Jun 21, 2016 at 09:30 PM
I am not the best coder, but you dont have the sam setup for the if function on both the Scenemanager.ActiveScene etc , the ) is not in the same place You could try that if that werent on purpose
Answer by manelizzard · Jun 23, 2016 at 02:13 PM
One thing you can do is use DontDestroyOnLoad in its very simple way, and create two public functions: Play and Pause. Then, on each scene, in its Start method, find the AudioManager object and Play/Stop it as desired.
using UnityEngine;
using System.Collections;
using UnityEngine .SceneManagement ;
public class AudioManager : MonoBehaviour {
public AudioSource BGM;
void Start(){
Play();
DontDestroyOnLoad (gameObject);
}
public void Play() {
BGM.Play();
}
public void Stop() {
BGM.Stop();
}
}
Your answer
Follow this Question
Related Questions
master background music toggle not working after changing scenes 1 Answer
Audio from scene 1 & 2 continues to play in scene 3 even though it was not added to scene 3. 1 Answer
How can I check the scene and play audio accordingly? 1 Answer
AudioSource not playig after switching between scenes 0 Answers
Play Sound On Object In Another Scene With Button from First Scene 1 Answer