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..?
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:
- turn the room collider into a Trigger if it isn't already
- attach a new script to the room. Let's call that behavior
- Add a variable
public AudioClip backgroundMusicto the script. This allows you to assign the desired background music clip for the zone in the inspector.
- Add an
OnTriggerEntermethod to that script. Implement that method to:
- check if the object which just entered is the player
- if so obtain the audio source component from the main camera using
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.