In our application we want to have music playing constantly. We can accomplish this by attaching a GameObject
to the player or camera object and having the music play from there. If you attempt this, your sound system will play music just fine until the scene changes. As such, the primary difference between playing sound and building a music system is making sure that the music keeps playing.
Music
..mp3
file into the game project. In the project's sample files you will find the track Orc March by basematic. You can find other creative commons music at http://www.ccmixter.org/:scene_2
.MusicPreserver
and fill it with the following code:function Awake() { // find the music player object var musicObject : GameObject = GameObject.Find("MusicPlayer"); // make sure we survive going to different scenes DontDestroyOnLoad(musicObject); }
We can now play music in our game and have that music active as we move across scenes. This will give us the ability to set moods for areas of our game, yet give the flexibility of being able to change the scene data while the music continues to play.
By default, when Unity loads a new level or scene, all of the objects in the previous scene are destroyed (which would normally stop our music). The key to preserving the music is the DontDestroyOnLoad
method which will tell Unity to leave this Game Object alone when it is disposing of objects from the original scene. Now we can have real music sound tracks that span our entire game.
18.118.138.33