Reputation: 646
I'm sort of new to Unity, so please don't be annoyed if you think that this isn't enough code, or an extremely simple mistake. So, I have a button, it says Autorestart. When I click it, it should turn from false to true. It does not. Here are screenshots and code. Thank you! Tell me if you need more code, but I don't think you do.
Before:
After clicking Autorestart: false, it should have turned to Autorestart: true
Here is some code
using UnityEngine;
using UnityEngine.UI;
public class manageautorestart : MonoBehaviour {
public Text text;
void Start(){
if (PlayerPrefs.HasKey ("autorestart")) {
text.text = "Autorestart: " + PlayerPrefs.GetString ("autorestart");
} else {
PlayerPrefs.SetString ("autorestart", "false");
text.text = "Autorestart: " + PlayerPrefs.GetString ("autorestart");
}
}
public void Change(){
if (PlayerPrefs.GetString ("autorestart") == "false") {
PlayerPrefs.SetString ("autorestart", "true");
}
if (PlayerPrefs.GetString ("autorestart") == "true") {
PlayerPrefs.SetString ("autorestart", "false");
} else {
PlayerPrefs.SetString ("autorestart", "false");
}
PlayerPrefs.Save ();
}
void FixedUpdate(){
PlayerPrefs.Save ();
text.text = "Autorestart: " + PlayerPrefs.GetString ("autorestart");
}
}
Upvotes: 0
Views: 1936
Reputation: 10701
My first choice would not be to use a string to store a boolean.
You could use :
public class manageautorestart : MonoBehaviour
{
public Text text;
void Start()
{
SetText();
}
public void Change()
{
bool autorestart = GetAutorestart();
// flip the value
autorestart = !autorestart;
SetAutorestart(autorestart );
SetText();
}
private bool GetAutorestart()
{
// Get stored value, 0 if none
int temp = PlayerPrefs.GetInt("autorestart", 0);
// convert 0/1 to false/true
autorestart = (temp == 1) ? true : false;
return autorestart;
}
private void SetAutorestart(bool value)
{
// store it as int
PlayerPrefs.SetInt("autorestart", value ? 1 : 0);
}
private void SetText()
{
text.text = "Autorestart: " + GetAutorestart();
}
}
You now have three distinct methods to set/get the value and place it in the text. The Change method makes use of all three.
Upvotes: 2