- Home /
saving button text
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.
Answer by shrey150 · Jul 18, 2017 at 12:50 PM
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.
Thank you so much. It worked. muteText is to change the text of the Sound on/off button. I tried toggle button but was having same problem(saving its on/off status) with it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612130535im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
OnGUI button changes size for resolution, but text doesnt? 1 Answer
How to change button text via script? 2 Answers
Dynamically generate buttons from a single text component 0 Answers
Null reference when I already assign a value? (UI Button and Text) 1 Answer
How do I set a GUI button's text using a string from another script? 0 Answers