Mute Toggle Not Staying On
I have been trying to figure this out for a week now. A this point I am completely at a loss.
What I am trying to do is have a UI Toggle act as the mute button. I have a main menu, a main level and a death screen. When I click the toggle on the main menu and continue to the next scene (the main level) the game stays muted, but the check mark is no longer present in the toggle and I have to click the mute button once to get the toggle back and then click it again to unmute the game. The same issue is happening upon entering the death menu. The death menu restarts the level and ends up unchecking the the UI toggle when it resets.
I have tried saving to player prefs. I have tried DontDestroyOnLoad.... I have tried MANY things. All I want is a mute toggle that persists through scenes and through application quit.
Here is the code I currently have. At this point I have modified it so many times I am not sure if this code is working or not.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MuteToggle : MonoBehaviour {
bool isMute;
void Start()
{
PlayerPrefs.GetInt ("MuteToggle");
}
// Use this for initialization
public void MuteButton ()
{
isMute = ! isMute;
AudioListener.volume = isMute ? 0 : 1;
PlayerPrefs.SetInt ("MuteToggle", 1);
PlayerPrefs.Save();
}
}
At this point I would do anything for someone to walk me through this.
in Start your getting the value but you don't save it, probably should read:
is$$anonymous$$ute = PlayerPrefs.GetInt...
I will try this again, but I am pretty sure it says I can't do that because is$$anonymous$$ute is a bool. I am not in front of my computer at the moment, but I will be in about an hour and I will plug that in and try it.
I updated my script, but it is giving me the bool error I mentioned earlier
Answer by FailureToAdapt · Jan 04, 2017 at 08:51 PM
Eventually I found the answer I was looking for through a tutorial on Youtube. This One
I ended up attaching this code to my main menu script:
public void ToggleSound()
{
if (PlayerPrefs.GetInt ("Muted", 0) == 0)
{
PlayerPrefs.SetInt ("Muted", 1);
} else {
PlayerPrefs.SetInt ("Muted", 0);
}
SetSoundState();
}
private void SetSoundState()
{
if (PlayerPrefs.GetInt ("Muted", 0) == 0) {
AudioListener.volume = 1;
audioOnIcon.SetActive (true);
audioOffIcon.SetActive (false);
} else {
AudioListener.volume = 0;
audioOnIcon.SetActive (false);
audioOffIcon.SetActive (true);
}
}
Answer by Kiefy · Jan 03, 2017 at 08:16 PM
So you're reading the PlayerPrefs value for MuteToggle but it doesn't appear that you're applying it.
I'm pretty new to this myself, but try adding in Start():
// in case there's a bool<->int conversion issue
isMute = PlayerPrefs.GetInt ("MuteToggle") ? true : false;
AudioListener.volume = isMute ? 0 : 1;
and when saving:
PlayerPrefs.SetInt ("MuteToggle", isMute ? 1 : 0;
PlayerPrefs.Save();