Easiest way to save a List variable to PlayerPrefs in Unity



Using PlayerPrefs in Unity is very useful to save and load user/player’s game data.

But, problem is our player data is not always as simple as single string, or integer or float value of variable.

For example, how do we store a List to PlayerPrefs?

My favorite way to do it is to convert the List to a single line of string with comma separator.

string datastring = string.Join(",", yourListHere);

Now your datastring contains a comma separated items such as “bag,toothpaste,chair,blabla”

Then you can save that string to PlayerPrefs like this:

PlayerPrefs.SetString("CollectedItems", datastring);

Then you can simply retrieve it by calling PlayerPrefs.GetString…

string datastring = PlayerPrefs.GetString("CollectedItems");

And how to convert the comma separated string to our original List? Take a look at this example:

yourListHere = datastring.Split(',').ToList();

But you need to use System.Linq for this last line.

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *