0

I want to be able to save and load all attributes of this PlayerStats class to and from a binary file. Do Weapon and PlayerClass need to be serializable too?

The weapons array contains classes that inherit from Weapon such as Pistol and Rifle. Would they also need to be serializable?

[Serializable]
public class PlayerStats : Saveable<PlayerStats> {
    private Weapon[] weapons;
    private PlayerClass activeClass;
    // ...
}

I've already done this successfully with another class, but the only attribute the class had was a dictionary.

edit, this is what I'm trying to use to serialize that works with my other more simple class but not the PlayerStats class:

public abstract class Saveable<T> {

    #region BinarySaveable

    public virtual void saveInstanceToBinaryFile(T instance, string fileName) {
        BinaryFormatter formatter = new BinaryFormatter ();
        Stream stream = new FileStream (fileName, FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, instance);
        stream.Close ();
    }

    public virtual T loadInstanceFromBinaryFile(string fileName) {
        BinaryFormatter formatter = new BinaryFormatter ();
        Stream stream = new FileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        T instance = (T)formatter.Deserialize (stream);
        stream.Close ();

        return instance;
    }

    #endregion

If this were Java I'd probably be able to just use the WriteObject(Object obj) method.

James T.
  • 910
  • 1
  • 11
  • 24
  • Assuming you are using `BinaryFormatter`, then yes, all objects in the graph must be `[Serializable]` unless you use a surrogate, as shown [here](http://stackoverflow.com/q/13166105/3744182) or [here](http://stackoverflow.com/a/42798279/3744182) - the latter of which was tested in unity3d. Have you tested it yourself? – dbc Mar 31 '17 at 23:05
  • 3
    Not related to your question but I want to mention that serialization in unity is not recommended by most users. plain text solutions such as JSONObject is much simpler and more efficient. – Bizhan Mar 31 '17 at 23:18
  • 2
    I've been using Unity for a long time and I agree with @Bijan that you should use [json](http://stackoverflow.com/a/36244111/3785314) if you want to serialize a class. There are so many problems with `BinaryFormatter` in Unity. – Programmer Apr 01 '17 at 01:22
  • @Programmer What problems are you referring to? – dogiordano Apr 02 '17 at 21:29
  • 1
    @dogiordano One is example is when you add new variable to the class. You can't load the old data saved. This causes problems when you want to update your game. – Programmer Apr 03 '17 at 02:13

1 Answers1

0

Yea, it seems they do.

It's much easier to conform to using JsonUtility.ToJson(myObject); in Unity than doing it myself.

https://docs.unity3d.com/Manual/JSONSerialization.html

James T.
  • 910
  • 1
  • 11
  • 24