- Home /
How to start new audio-track and switch off prior audio-track when player is back at main menu?
with the main menu which is an own scene and shown at the beginning there also starts an audio file. In the options of the main menu I am able to change the volume of the audio file. However, I used the following lines of code in the audio-script that if another scene loads (game level) the same audio will still be played:
public void Awake()
{
DontDestroyOnLoad (transform.gameObject);
}
So I also have a pause menu where I have the option to go back to the main manu and here starts the problem: When I am back at the main menu another object of the audio file will be created which means that always I come back to the main menu it adds another track of the audio file which obviosly is not desireable. What can I do that the audio file will be played the first time the main menu is shown at the beginning and each time I come back to the main menu (via the pause menu) then the audio file has to start new?
Do you have a single script that is responsible for playing audio? If not, maybe do that and make it a do not destroy on load, and a singleton. Then have your methods play audio clips for whatever scene and a single audio player that you can stop. hmm... that's a little hard to explain see below rough idea:
class AudioStuff : $$anonymous$$onobehavior {
public static AudioStuff instance; // singleton
public AudioPlayer player;
private void Awake()
{
if (instance == null) { instance = this; dontDestroyOnLoad(gameObject); }
else destroy (gameObject);
}
public void PlayGameLevelAudio() {
player.Stop();
// play new audio here.
}
public void Play$$anonymous$$ain$$anonymous$$enuAudio() {
player.Stop();
// play new audio here.
}
}
Then in your class for the menu in start you can do
AudioStuff.instance.Play$$anonymous$$ain$$anonymous$$enuAudio();
This will stop the current clip playing and load the new audio for the scene.
Your answer
![](https://koobas.hobune.stream/wayback/20220613021657im_/https://answers.unity.com/themes/thub/images/avi.jpg)