I'm making a player settings thing where the user can turn off or turn on the game music by clicking buttons. I had this script below and everything was working fine.
private GameObject music;
public void Start()
{
music = GameObject.FindGameObjectWithTag("Music");
}
public void YesButton()
{
music.SetActive(true);
}
public void NoButton()
{
music.SetActive(false);
}
I want to save it as player preferences so when they go out and back into the game, their settings would be saved. How would I do this? This is what I tried:
private GameObject music;
private bool musicOn = true;
public void Start()
{
music = GameObject.FindGameObjectWithTag("Music");
}
public void YesButton()
{
musicOn = true;
PlayerPrefs.GetInt("MusicOn", (musicOn ? 1 : 0));
}
public void NoButton()
{
musicOn = false;
PlayerPrefs.GetInt("MusicOn", (musicOn ? 1 : 0));
}
void Update()
{
PlayerPrefs.SetInt("MusicOn", (musicOn ? 1 : 0));
int value;
value = musicOn ? 1 : 0;
if (musicOn)
{
value = 1;
music.SetActive(true);
} else if (!musicOn)
{
value = 0;
music.SetActive(false);
}
}
But it doesn't work. When I click the "no" button, the music turns off but it turns back on when I go back into the game. How would I fix this problem? Thanks for your help!
New code that mostly works:
public GameObject music;
public bool musicOn = true;
public void Start()
{
music = GameObject.Find("Music");
bool musicOn = PlayerPrefs.GetInt("MusicOn", 0) > 0;
if (musicOn)
YesButton();
else
NoButton();
}
public void YesButton()
{
music.SetActive(true);
PlayerPrefs.SetInt("MusicOn", 1);
}
public void NoButton()
{
music.SetActive(false);
PlayerPrefs.SetInt("MusicOn", 0);
}