Introduction
In this article we see how to SAVE STRINGS in Unity using the PlayerPrefs class, to store information in the persisten memory, then we see how to load those strings from memory to recover the information. An application of this method could be for example save the player’s name in memory.
How to save a String with PlayerPrefs
To save a String in Unity using PlayerPrefs we’ll use the static method “SetString”, a function that needs 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 String data that we want to store.
The instruction that will do the saving of the data in Unity would look like this:
PlayerPrefs.SetString(“stringDataName”,stringData);
In this case we indicate the name of the data between quotes because it’s a string, the second parameter we indicate it using a string type object.
How to load a String with PlayerPrefs
To load a String into Unity using PlayerPrefs we’ll use the static “GetString” method, 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 “SetString” function we saw before. We do it in the following way.
stringData=PlayerPrefs.GetString(“stringDataName”);
The execution of the static method “GetString” of PlayerPrefs results in a string data, that’s why it is assigned to the obhect “stringData” in the above instruction.
The second way is also to give it the name of the data that we use in the execution of “SetString” 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.
stringData=PlayerPrefs. GetString(“stringDataName”,””);