I am making a music ON/OFF button. I am using button text to show on/off. It is working okay but as soon as I change the scene the “OFF” text is turning back to “ON”. I want to save its status. I searched everywhere but couldn’t find anything. Tried Playerprefs but failed. here is my code.
void Start()
{
if (PlayerPrefs.HasKey ("music"))
{
PlayerPrefs.GetFloat ("music");
}
}
public void MuteToggle(){
isMute = !isMute;
if (isMute == true) {
AudioListener.volume = 0;
muteText.text = "OFF";
PlayerPrefs.SetFloat ("music", 0);
} else {
AudioListener.volume = 1;
muteText.text = "ON";
PlayerPrefs.SetFloat ("music", 1);
}
}
I tried with toggle too but couldn’t succeed.
It doesn’t actually look like you’re saving or applying PlayerPrefs.GetFloat("music")
anywhere. Why not try something like this:
void Start() {
float music = PlayerPrefs.GetFloat("music", 1.0f);
AudioListener.volume = music;
if (music == 1.0f) {
muteText.text = "ON";
isMute = false;
} else {
muteText.text = "OFF";
isMute = true;
}
}
Replace your current Start()
function with this, and at the start of the scene it’ll be applied.
Two things I’d suggest: use Set/GetInt()
instead of float, if you plan to only have a toggle music button. If you plan to do a slider setup, then float is the way to go.
Secondly, your variable name, muteText
, is a bit confusing. In my code snippet I followed your usage, but really if mute is on, volume is 0. Maybe change the name to musicText or something. Just a thought.