How can I save a string array to PlayerPrefs in Unity?

Viewed 1844

I have an array and I would like to save it to PlayerPrefs. I heard, I can do this:

PlayerPrefs.SetStringArray('title', anArray);

but for some reason it does not work. Maybe I'm not using some library like using UnityEngine.PlayerPrefs;?

Can someone help me?

Thanks in advance

1 Answers

You can't. PlayerPrefs doesn't support arrays.

But you could use a special separator and do e.g.

PlayerPrefs.SetString("title", string.Join("###", anArray));

and then for reading use

var anArray = PlayerPrefs.SetString("title").Split(new []{"###"}, StringSplitOptions.None);

Or if you know the content and in particular which character is never used you could also use a single char e.g.

PlayerPrefs.SetString("title", string.Join("/n", anArray));

and then for reading use

var anArray = PlayerPrefs.SetString("title").Split('/n');

Yes as TEEBQNE mentioned there is PlayerPrefsX.cs which might be the source of the confusion.

I would NOT recommend it though! It simply converts all the different input types into byte[] and from there to Base64 strings.

That might be cool and all for int[], bool[], etc. But for string[] this is absolutely inefficient since the Base64 bytes representation of a string is way longer than the string itself!

It might be a valid alternative though if you can not rely on your strings contents and you can not be sure that your separator sequence is never actually a content of any string.

Related