|
I'm trying to play background music through multiple scenes by creating a Game Object in my main menu and using the code below:
In my Menu script...
The music keeps playing when I go to other scenes, but it stops once I return to the main menu.
(comments are locked)
|
|
If you use DontDestroyOnLoad(gameMusic) it will "survive" a scene load. In you first script you are destroying the gameMusic object manually every time you load a new scene. If you don't do that it should work. To use the Singleton pattern just replace the class name with your own. Then add you own code to it. You can now reach this object from every other script using MyClassName.Instance. Here is the quick and dirty version for you:
If you attach this script to your gameMusic object the object shouldn't be destroyed and you can start stop your music by calling MusicPlayer.Instance.Play() from any script. How do I connect my music game object to the instance?
Oct 23 '10 at 08:41 AM
Lanipoop
You don't "connect" it to the Singleton, your music gameObject IS the singleton.
Oct 23 '10 at 09:02 AM
StephanK
Err.. I'm sorry, but where am I supposed to put "gameMusic"? I edited my original post to what I have now.
Oct 23 '10 at 09:11 AM
Lanipoop
Thank you, spree! It's looking a lot better now. But for some reason, whenever I go back to the menu, the music actually stops. And if I go to a different scene and come back, it'll play again. I changed my original post to show you what I have right now.
Oct 23 '10 at 09:22 AM
Lanipoop
That's because every time your menu script starts up it restarts your MusicPlayer. You should check if the audio is already playing before you start it. You can use audio.IsPlaying for that.
Oct 23 '10 at 11:02 AM
StephanK
(comments are locked)
|
|
Messing around with the code a bit and testing with my game I have found the code below to work. The music plays throughout all scenes and doesn't start and stop when going in and out of the menu. I also just Play the music within the class for when the instance first gets set to this. Don't know if this is sloppy c# coding, but still just getting my feet wet with this language.
(comments are locked)
|
|
This is what I finally cobbled together that worked for me.
(comments are locked)
|

Lani, did you ever solve this problem? What you described sounds kind of like a (possible) Unity bug I've been trying to isolate, so I'd be curious to know how this turned out.
Unfortunately, I was not able to fix this. I ended up just making a loading screen and putting the music there. :(
Thank you both for the effort, though! Much appreciated :)