0
\$\begingroup\$

In Unity 2019.3.0a2 I have a labyrinth with multiple rooms. I want the music to change when I get from one room into another. How can I do it so that music from room 1 is only hearable in room 1, and so on..?

the current model

\$\endgroup\$
4
\$\begingroup\$

If you want to play non-diegetic music (background music which just plays without a positional source), then a simple solution is to add the audio source which plays that music directly to the camera.

Now when the player enters a collider, you can just change the audio clip played by that audio source. In order to do that:

  1. turn the room collider into a Trigger if it isn't already
  2. attach a new script to the room. Let's call that behavior BackgroundMusicZone.
  3. Add a variable public AudioClip backgroundMusic to the script. This allows you to assign the desired background music clip for the zone in the inspector.
  4. Add an OnTriggerEnter method to that script. Implement that method to:
    1. check if the object which just entered is the player
    2. if so obtain the audio source component from the main camera using Camera.main.GetComponent<AudioSource>()
    3. use audioSource.Play(backgroundMusic) to switch to the new audio clip.

Now this is a very basic solution which immediately switches from one music to another. A better solution might be to fade from one music to another by gradually reducing the volume while the old music is still playing and then switching to the new music. This could be done with a coroutine or by going through the audio mixer which has the ability to transition between two setting snapshots. This requires two audio sources attached to different mixer groups: One for the old music and one for the new one.

You might also implement some functionality to only switch to the new music when the player stays in the BackgroundMusicZone for a while to avoid rapidly switching between two tracks when the player moves back and forth between two areas.

\$\endgroup\$
  • \$\begingroup\$ Thank you so much! I will try it out. You helped a lot! \$\endgroup\$ – heavenandu Jun 3 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.