2

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
  • 1
    Please include where you saw this PlayerPrefs.SetStringArray code
    – Ruzihm
    May 10, 2021 at 20:26

1 Answer 1

7

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.

10
  • There is PlayerPrefsX, which I believe what OP is referring to when referencing SetStringArray. It is not vanilla PlayerPrefs, but I think they are just getting them confused.
    – TEEBQNE
    May 10, 2021 at 19:00
  • That uses underlying bytes and base64 strings .. which sounds pretty inefficient though .. so basically in the end it uses SetString and GetString for everything but the base64 bytes representation of a string is usually longer the the original string itself afaik
    – derHugo
    May 10, 2021 at 19:02
  • I prefer your solution. I just wanted to mention it to clear up where SetStringArray comes from.
    – TEEBQNE
    May 10, 2021 at 19:05
  • 1
    @TEEBQNE yeah I see, good to know of course. Just wanted to make clear for OP that it's not really the best idea to use that ;)
    – derHugo
    May 10, 2021 at 20:01
  • 2
    @Some-Guy as said it's not good to use that .. if you really want to anyway - against all advices .. well you simply go to the link of TEEBQNE and copy the content of the PlayerPrefsX.cs scripts as a new script into your project .. I wouldn't though but rather use mentioned Join/Split which is way more efficient
    – derHugo
    May 10, 2021 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.