I have a level in a 2D platformer game that I want to have a few audio transitions. The top part of the map I want to have 1 song play as soon as the player enters the level. There’s a long section where the user falls and I don’t want there to play any audio. Then in the final room I want a totally different song to play. I was aware that the min distance and area affected where the audio would be played. However when I have both audio objects in place and with their specific area, both songs play at the same time.
But that’s not how I would handle this here … I would do this by just triggering the audiosource.play based on the events of the level (player falling = stop first audio and play next audio). Since there’s a silent gap between the two musics this is perfectly fine.
Thank you very much, but I ended up writing a script:
using UnityEngine;
public class SoundOff : MonoBehaviour {
public AudioClip nextMusic; // drag the next music here in the Inspector
public AudioSource audioObject; // drag the music player here or...
void Start()
{ // find it at Start:
// supposing that the music player is named "MusicPlayer":
audioObject = gameObject.GetComponent<AudioSource>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{ // only an object tagged Player stops the sound
audioObject.Stop();
Debug.Log("Player entered!");
}
}
void OnTriggerExit2D(Collider2D other)
//use ontriggerexit 2D instead of no 2D because of collider
{
if (other.tag == "Player")
{ // only an object tagged Player restarts the sound
audioObject.clip = nextMusic; // select the next music
audioObject.Play(); // play it
Debug.Log("Player exit!");
}
}
}