- Home /
How To Save and Automatically Load each Toggle CheckBox Value ?
How can we store each of the checkbox value, that the next time we open the scene it can be automatically loaded ? Here's the code I have now:
using UnityEngine;
using UnityEngine.UI;
public class SettingsController : MonoBehaviour
{
bool[] settings;
public Toggle[] toggles;
void Start()
{
settings = new bool[toggles.Length];
for (int i = 0; i < toggles.Length; i++)
{
settings[i] = true;
int index = i;
Toggle t = toggles[i];
t.onValueChanged.AddListener(
(bool check) =>
{
CheckBox(index, check);
}
);
}
}
public void CheckBox(int index, bool check)
{
settings[index] = check;
}
}
Answer by SamuelRoos · Jun 07, 2020 at 03:28 AM
You could use Unity's PlayerPrefs for saving the toggle states. Since there is no method for saving booleans, you'd need to use an integer value as a bool (0 as false and 1 as true).
You can save a state of an individual toggle to the PlayerPrefs like so:
//Let us imagine that up here is a *for loop* looping through all the toggles.
//isOn returns the current state of a toggle as a bool
//we convert this boolean to an integer using a *ternary conditional operator*
//it's basically an if statement but within one line.
int currentToggleState = toggles[i].isOn == true ? 1 : 0;
//SetInt takes in two parameters; the key as a string + the actual value which is in this case an integer.
PlayerPrefs.SetInt("NameOfThisParticularToggle", currentToggleState);
//Boom, the value is now saved in the PlayerPrefs and will remain there forever until destruction
//PlayerPrefs.DeleteAll() to clear them all, though be careful using this command
Now, if you wanted to load the value from the PlayerPrefs upon loading a scene, this is how you'd deal with that:
//Again, here would be a for loop... too lazy to write it :)
//Converting the integer back to a boolean using the conditional operator.
toggles[i].isOn = PlayerPrefs.GetInt("NameOfThisParticularToggle") == 1 ? true : false
And here you go, this is how you'd do it.
Also, if you're struggling how to get the right PlayerPrefs value to a corresponding toggle when using a for loop (for example getting a saved int named as "GraphicalQuality" to the toggle which controls the quality), you could simply name all the toggle gameobjects differently, then save them to the PlayerPrefs by their gameobject names and then load the PlayerPrefs value which is named exactly like the current toggle, like so;
//saving the value
PlayerPrefs.SetInt(toggles[i].gameObject.name, toggles[i].isOn == true ? 1 : 0);
//and loading it...
bool isOn = PlayerPrefs.GetInt(toggles[i].gameObject.name) == 1 ? true : false
Also also, you will most likely get a error first time you load up the game as you haven't yet saved any player prefs though you are still trying to get them. You could do some checking based on if there is actually anything in the playerprefs, and if not, create them first.