0

If I have a class and I make it Serializable because I want to save the state. How do I get that state back?

[Serializable]
public class MyObject 
{
  public int a = 5;
}

Related post where I learned about Serialization What is [Serializable] and when should I use it?

Community
  • 1
  • 1
user3795475
  • 107
  • 1
  • 1
  • 5

2 Answers2

0

If you want to change and save the state at runtime, a class with the Serializable attribute is the wrong way to go.

My guess is that the PlayerPrefs will be good enough for what you are looking for. You could do something like this:

public static string playerPrefKey_a = "a_value";
public static int a
{
    get { return PlayerPrefs.GetInt(playerPrefKey_a); }
    set { PlayerPrefs.SetInt(playerPrefKey_a, value); }
}
Formic
  • 650
  • 5
  • 7
0
    /// <summary>
    /// (extension method) Deserializes a byte array into an object.
    /// </summary>
    public static T DeserializeToObject<T>(this byte[] buffer) where T : class
    {
        using (var stream = new MemoryStream(buffer))
        {
            var formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
  • Please add reasons for down voting for learning purposes. Thank you –  Jul 02 '14 at 04:06