- Home /
Saving settings info in between scenes
I have 2 scenes a menu & a game in the menu it has settings where the sound effects are on or off on a button. how do I save the sprite image icon on the button and whether the sound is on or not? I messed around with PlayerPrefs but just don't know how to use it.
public Sprite onSprite, offSprite;
public Button but;
public AudioSource click;
public bool sound ;
void Start ()
{
click = GetComponent<AudioSource>();
}
public void SFX ()
{
click.Play();
if (but.image.sprite == onSprite)
but.image.sprite = offSprite;
else
{
but.image.sprite = onSprite;
}
sound = !sound;
if (sound)
{
click.enabled = true;
}
else
{
click.enabled = false;
}
Answer by michi_b · Oct 25, 2018 at 05:45 AM
You can easily use PlayerPrefs for that. Just initialize the button from PlayerPrefs like so:
void OnEnable()
{
but.image.sprite = (PlayerPrefs.GetInt("IsSoundOn", 0) == 1) ? onSprite : offSprite;
}
So a 1 in the setting with the key "IsSoundOn" means that the onSprite is to be used, otherwise its offSprite. Then you also have to write back that value to persistent storage when the menu is closed.
void OnDisable()
{
PlayerPrefs.SetInt("IsSoundOn", but.image.sprite == onSprite ? 1 : 0)
}
So the next time the menu is opened, in the same scene/game session or not, the same sprite is assigned again. Since I used OnEnable and OnDisable for restoring/saving, This will work as long as there is maximally one such button enabled at the same time. Make sure the key, in this example "IsSoundOn" is shared across buttons/menus that control/display the same setting.
Your answer
Follow this Question
Related Questions
Unity - keep created buttons after quit 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
PlayerPrefs for Mute/Unmute button 1 Answer