How do i stop music from playing when i switch back to game after press home button?

Hi guys

I'm using this script to disable in-game music.

function Update () {
if (!gamemusicmanager.musicon)
{
AudioListener.pause = true;
}
else
{
AudioListener.pause = false;
}
}

the code works fine when i play game. But, when i press "Home" button to do something else, and later switch back to the game, the music continues to play for some seconds (when the game screen hasn't appear yet) and then acts normal just like when i turn it off.

I guess the AudioListener is loaded before the scene?

This seems pretty annoying. How can i stop that?

Thanks

PS: Script attached to the main camera . I guess i must replace update with something else?

3 Answers

3

Any one? :( This is insane :(

Maybe you should stop or pause the AudioSource(s) instead of disabling the listener:

audio.Pause();

audio.Stop();

I am not sure how it works on an Android ... Sorry.

use OnEnable() instead of Start() that will get called ever time your object is activated, loaded, or if the script it self is set to enabled after being set to disabled. If you don't want your audio listener to be on as soon as it loads in then you can disabled it in the scene and then enable it at runtime once the scene has loaded. Unity will spit out a few warnings saying there must be 1 audio listener but this is harmless.

i know this is a very old question, but i struggled with this problem myself and now i did this this way:

first i have a PlayerPrefs for my mute with 1 and 0 for muted and not muted. then i use i private int mute to look if sound should be muted or not.

then i have this Update function:

	void Update() {

		if (mute == 1 && AudioListener.pause == false) {
						AudioListener.pause = true;
				
		}

	}

this is working for me! Sorry if this isn’t a good way, but i started programming earlier this year and i started with unity about 4 or 5 weeks ago!