Okay - I want to be able to fade a music track at any time so that it fades in and starts with another music track in Unity at a certain point (for example when close to a box or another object)
The reason I mentioned Pokemon is because the games do exactly what I want to recreate in Unity when the player moves from town to town or route to route. They fade out at any point when the user moves to another area and start another music track when the player enters a different location.
Any ideas how I could recreate that in Unity? If you have any suggestions I’d love to hear them.
For the sake of demo codes that anybody might drop here to let me know I’ll call the two tracks I want to use:
If the tracks will never overlap one another, you can use a single audio source for this; otherwise, you can use multiple audio sources.
I don’t think Unity has any built-in support for fades, so you’ll probably need to write a simple ‘fade’ script that, when instructed to do so, begins a fade-in or fade-out with a specified duration. (You can change the volume by setting the ‘volume’ field of the audio source directly.)
How to detect when the player has entered or left an area is up to you, but a common solution would be to use triggers. Once you have that part figured out, when the player leaves an area, instruct the ‘fade’ component for the corresponding music track to begin fading out. When the player enters an area, instruct the ‘fade’ component for the corresponding music track to begin fading in.
That method will most likely lead to volumes outside of the range [0,1]. This may not have any practical implications (Unity might clamp these values internally), but you might want to clamp the value explicitly just for clarity.
I touched on this in my previous post. The exact details are going to depend on the specifics of your project, but you have at least a couple of options:
Have a separate sound source for each music track, and control the volume of each as in your example. If the source positions and distance thresholds are set up appropriately, switching of music tracks should occur naturally. (You’ll probably also want to add some logic to stop playback of a track when the volume reaches zero and start playback when it first becomes non-zero, just to save system resources.) Note that this approach would probably make the most sense if the sound sources are localized.
Use a single sound source. Assign to your ‘music playing’ component a list of audioclips representing the different tracks. As the player moves from area to area, in addition to adjusting the volume, assign the appropriate track to the audio source ‘clip’ field as well. (This assumes that the music is non-localized.)