Wednesday, January 12, 2011

Store objects in PlayerPrefs.

Usage:
var myObject = new MyClass();
Prefs.Save<MyClass>("my object", myObject);
var anotherObject = Prefs.Load<MyClass>("my object")


or something like that...

using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
using System.IO;


public class Prefs
{

public static void Save<T> (string name, T instance)
{
XmlSerializer serializer = new XmlSerializer (typeof(T));
using (var ms = new MemoryStream ()) {
serializer.Serialize (ms, instance);
PlayerPrefs.SetString (name, System.Text.ASCIIEncoding.ASCII.GetString (ms.ToArray ()));
}
}

public static T Load<T> (string name)
{
if(!PlayerPrefs.HasKey(name)) return default(T);
XmlSerializer serializer = new XmlSerializer (typeof(T));
T instance;
using (var ms = new MemoryStream (System.Text.ASCIIEncoding.ASCII.GetBytes (PlayerPrefs.GetString (name)))) {
instance = (T)serializer.Deserialize (ms);
}
return instance;
}

}

2 comments:

Anonymous said...

That's hot!

Bernard said...

Cool!

Note that if you're saving a lot of data like this, it could become very slow on Android and iOS.

We made a custom PlayerPrefs class that can be used for this, to make this faster:
http://www.previewlabs.com/writing-playerprefs-fast/

Popular Posts