# UnityEngine.PlayerPrefs corrupts string?

I need to use PlayerPrefs to store arrays of bytes for my game. For some reason, the string I save with PlayerPrefs doesn't come out with the same length.

I.e.

byte[] TestArray = new byte[256];
for (byte i = 0; i < 256; i++)
{
TestArray[i] = i;
}

char[] charBuffer = new char[TestArray.Length];
for (int i = 0; i < TestArray.Length; i++)
{
charBuffer[i] = (char)TestArray[i];
}

PlayerPrefs.SetString ("Storage", new string(charBuffer));

PlayerPrefs.Save ();

Debug.Log (new String(charBuffer).Length);
Debug.Log (PlayerPrefs.GetString ("Storage").Length);


Log:

256
5


Is this possibly an issue with encoding? How do I fix it?

• Can you log what is inside the string? – Static May 31 '15 at 0:18
• One of the reasons I see is that one of the bytes you save is zero, which is often the representation of a end of string. So when you reload that string, the ".Length" attribute will be set at the first occurrence of zero (\0). – Vaillancourt May 31 '15 at 0:24
• Thanks for the quick feedback. It turns out that it was an encoding problem. The contents of the string were pretty gibberish and some of them, Unity wasn't capable of printing which is why I only printed the length. – JPtheK9 May 31 '15 at 0:27

I browsed the UForums and found a solution. It turns out, Unity serializes strings in base64 so to save/extract data to/from a string, one has to save the data in that encoding. I'm not too keen on this subject, but this is what I did to make it work:

byte[] TestArray = new byte[256];
for (byte i = 0; i < 256; i++)
{
TestArray[i] = i;
}

PlayerPrefs.SetString ("Storage", System.Convert.ToBase64String (TestArray));

PlayerPrefs.Save ();

Debug.Log (System.Convert.ToBase64String (TestArray).Length);
Debug.Log (PlayerPrefs.GetString ("Storage").Length);


Log:

256
256


Could just be lazy and convert to hex if the bin is not too large. Best way to deal with encoding issues is to skip them.