1
\$\begingroup\$

I am giving the user a UI button to mute and unmute the ingame sounds but the problem is when I mute the sounds and then when the game ends and the game scene reloads the sounds comes back up which is really annoying.

After some searching I came to know that I need to use DontDestroyOnLoad(transform.gameobject); but it makes the copy of the whole thing and now I have two copies of the same music.

Also I don't know if this is the only way or not but just to mute/unmute an audio source it feels kind of overkill to me since I have a many components attached to my gameobject and then just to mute/unmute it copies the whole thing.

Can someone tell me how to fix that duplicating problem and also is there any simpler way to achieve this?

\$\endgroup\$
1
\$\begingroup\$

Another approach is to save a volume setting in Playerprefs from your button click function like this PlayerPrefs.SetFloat("Volume", 0f);

For the music object, attach a script and retrieve the volume setting in awake to set the volume on or off like this:

AudioSource audio_src;

void Awake(){
  audio_src = GetComponent<AudioSource>();
  audio_src.volume = PlayerPrefs.GetFloat("Volume", 1f);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I like this solution, as the preference is saved between game sessions, not just between scenes. \$\endgroup\$ Jun 7 '17 at 2:16
0
\$\begingroup\$

You could create a static class, and just use a static variable to set if the sound is muted or not.

public static class ApplicationData {
    public static bool SoundOn = true
}

In this manner, you access the variable like so:

ApplicationData.SoundOn 

This will allow you to retain the setting throughout your application.

This will not retain this data once the application closes however. If you want to retain this setting, you will need to look at storing it in PlayerPrefs before the application closes. And then load the setting from PlayerPrefs when you open the application again.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.