I have the following code:
public class MainMenuAudio : MonoBehaviour {
private static MainMenuAudio instance;
void Awake() {
if (MainMenuAudio.instance == null)
{
MainMenuAudio.instance = this;
GameObject.DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(this.gameObject);
}
}
void Start()
{
}
public void turnMusicOff()
{
if (instance != null)
{
this.gameObject.audio.Stop();
Destroy(this.gameObject);
MainMenuAudio.instance = null;
}
}
void OnApplicationQuit() {
MainMenuAudio.instance = null;
}
}
What it is supposed to do is to the keep the music going through the various menu scenes until you choose to start a game. Also it allows the game to start if the music is set to off in the options. The problem I am having is that when you exit the scene to another menu the music is not continuing. Yet when you return the music is playing.
Please help.
Note: The object is currently parented under the camera as has been suggested.
When it is unparented (at the top of the hierarchy). DontDestoryOnLoad works as expected, however it prevents the two game levels from loading, yet switches between menu scenes without issue. Additionaly it does not respond to the turnmusicoff function above when the music option is set to off.
Update 6/9/13: after 2 not so hopeful answers not even written in the correct language I came upon this.
http://answers.unity3d.com/questions/11314/audio-or-music-to-continue-playing-between-scene-c.html
So I first put the audio gameobject into the top hierarchy and changed the code to this so now it works.
public class MainMenuAudio : MonoBehaviour
{
private static MainMenuAudio instance;
void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
return;
}
else
{
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
void Start()
{
if (!instance.audio.isPlaying)
audio.Play();
}
public void turnMusicOff()
{
if (instance != null)
{
//if (instance.audio.isPlaying)
// instance.audio.Stop();
Destroy(this.gameObject);
instance = null;
}
}
void OnApplicationQuit()
{
instance = null;
}
}