How to save and load a bool variable with PlayerPrefs in Unity

Introduction

We’re going to see how to store bools in Unity using the PlayerPrefs class, then we’ll see how to load those bool values. This can be useful to save game states, for example if the player has already done some action.

How to save a bool with PlayerPrefs

PlayerPrefs doesn’t have a function to save logical values directly, so we’re going to save an integer that could be worth 0 or 1 depending on the state of the boolean variable, for this we use the static method “SetInt”, a function that needs us to give it two parameters.

The first parameter is a string with the name that will have this variable that we are going to store, this will allow that later we can recover it. The second parameter is the integer value that we want to store.

The instruction that will do the saving of the data in Unity would look like this:

PlayerPrefs.SetInt(“boolDataName”, boolData ? 1 : 0);

In this case we indicate the name of the data between quotes because it is a string, the second parameter we indicate it using the ternary operator “?:” that works as a simplified if statement, first we have the logical data we want to save, “boolData”, then the operator “?” and then the values it returns if boolData is true or false separated by “:”.

The expression “boolData ? 1 : 0” will result in 1 if boolData is true and 0 if boolData is false.

How to load a bool with PlayerPrefs

To load a bool into Unity using PlayerPrefs we have to remember that in the previous step we saved it as 0 if the variable is false or 1 if it’s true, so we retrieve the integer value using the “GetInt” function, a function that can be used in two different ways.

In the first form we give a parameter that is going to be the name of the data we want to retrieve, the name we gave it when we executed the “SetInt” function we saw before. We do it in the following way.

boolData =PlayerPrefs.GetInt(“boolDataName”)==1;

The execution of the static method “GetInt” of PlayerPrefs gives as a result an integer but by using the operator “==”, that compares if both expressions are equal, we get a logical result that we can assign to the “boolData” variable. If the stored integer is 1, boolData will be true, otherwise it will be false.

The second way is also to give it the name of the data that we use in the execution of “SetInt” but we also give a default value that will be used in case there is no data saved under that name, this is done in the following way.

boolData =PlayerPrefs.GetInt(“boolDataName”,0)==1;

Exit mobile version
Secured By miniOrange