Time for action – The sound of music

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.

  1. Create a folder called Music.
  2. Import your favorite .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/:
    Time for action – The sound of music
  3. Create an empty Game Object called MusicPlayer and make it the child of the Main Camera:
    Time for action – The sound of music
  4. Add an Audio Source component to the MusicPlayer Game Object.
  5. Next, we need to ensure that our MusicPlayer object does not get destroyed as we move between scenes, by creating a script in Unity that is attached to the next scene. To do this create a second scene in the game called scene_2.
  6. Create a script called 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);
    }
    
  7. Attach the MusicPreserver script to the new scene.

What just happened?

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.138.33