- Home /
Serializing PlayerPrefs
Hi guys
I saw this script here (http://forum.unity3d.com/threads/c-serialization-playerprefs-mystery.72156/) and even though it is old, I was wondering whether it could still work in your opinion:
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class PlayerPrefsSerializer
{
public static BinaryFormatter bf = new BinaryFormatter ();
// serializableObject is any struct or class marked with [Serializable]
public static void Save (string prefKey, object serializableObject)
{
MemoryStream memoryStream = new MemoryStream ();
bf.Serialize (memoryStream, serializableObject);
string tmp = System.Convert.ToBase64String (memoryStream.ToArray ());
PlayerPrefs.SetString ( prefKey, tmp);
}
public static object Load (string prefKey)
{
string tmp = PlayerPrefs.GetString (prefKey, string.Empty);
if (tmp == string.Empty )
return null;
MemoryStream memoryStream = new MemoryStream (System.Convert.FromBase64String (tmp));
return bf.Deserialize (memoryStream);
}
}
The reason I ask is that I am trying to serialize my PlayerPrefs, but when I use this, I see no difference in how the strings look in Registry. Any help would be welcome!
Alternatively, how do you guys serialize your PlayerPrefs if at all?
Cheers! :-)
There is no thing like "serializing player prefs", you can serialize your data THEN save it to the disk using player prefs...
About the code part, I used that same code as a base for $$anonymous$$e, with some improvements for generics and auto-casting to the correct value type, also improvements for saving other data structures.
If what you want is a better way to save you data, like hidding more your data to be more difficult to change it by hand, this code should handle good part of it.
Answer by LordDarkon76 · Jan 18, 2016 at 11:22 PM
If you need that for your save.
I'm currently using unitys JsonUtility.ToJson to make my stats class a json after a little codification(give some fun for the save hackers) save the string as a player prefs.
For loading I just use JsonUtility.FromJsonOverwrite and everything is ok.