Different approach to Music

I’ve moved to Unity 2017 now but the approach applies to 4 and 5 as well. I wrote a method which uses an array of audioclips and handles a single clip so the audio doesn’t restart at the start of every scene. if you specify 3 elements for laser defender, and attach the clip, it will play a different in each scene. Defaults to first element if no audio and doesn’t play if that is missing.

The method is as follows:

  private void PlayMusic()
  {
    int musicIndex = SceneManager.GetActiveScene().buildIndex;
    if ( MusicToPlay.Length == 1 && music.clip != null && music.isPlaying )
    {
      return;
    }
    if ( musicIndex >= MusicToPlay.Length || MusicToPlay[ musicIndex ] == null )
    {
      musicIndex = 0;
    }
    music.Stop();
    if ( MusicToPlay[ musicIndex ] != null )
    {
      music.clip = MusicToPlay[ musicIndex ];
      music.Play();
    }
  }

For unity 5/2017, call this from the delegate and for Unity 4.6, call from OnLevelWasLoaded. You’ll also need to change the way the index is obtained for 4.6

Privacy & Terms