- Home /
audio.isPlaying always returns false
I am trying to set music to play throughout the game and continue between scenes with an empty gameobject that has the script below attached on my main scene. It starts fine and when I move to other scenes it continues to play, but when I switch scenes back from another scene back to the main scene it plays a second instance. I am checking for isPlaying, but it always returns false. Is this because the gameobject is a new instance so I am not checking the original instance that is first created when the game starts?
function Awake () {
//Also checked for gameMusic as a boolean, but that didn't work either
//var gameMusic : GameObject = GameObject.Find("gameMusic");
//if(gameMusic){ audio.Play(); }
Debug.Log("is audio playing - " + audio.isPlaying);
if (!audio.isPlaying) {
Debug.Log("audio was not playing so it was started");
audio.Play();
}
DontDestroyOnLoad (transform.gameObject);
}
Sorry, I used to check for game$$anonymous$$usic as a boolean. Just forgot to take that out.
So original code was
if (game$$anonymous$$usic) { audio.Play(); }
Answer by Jesse Anders · May 03, 2011 at 05:21 PM
First of all, you search for a game object named 'gameMusic', but then you never use that reference.
Also, if you reload the scene that the 'game music' object is part of, a new instance of that object will be created. If you want only one 'game music' object, it should be part of a scene that's only loaded once (e.g. an 'intro' scene or something of that sort).
Answer by cozmoziz · May 03, 2011 at 06:29 PM
I found the answer with the help of using singleton's from this post. I've posted my answer here.
http://answers.unity3d.com/questions/24519/using-singleton-for-background-music
Your answer
Follow this Question
Related Questions
Keep audio playing even though I reset the scene 5 Answers
Changing Continuous Audio Between Scenes 0 Answers
I have a audio source in one scene, I want it to continue when entering next scene 1 Answer
Change music between scenes 1 Answer
Playing Music After Seconds Works, But When Scene Reloads, Script Doesn't Work 1 Answer