Search Unity

How to add two classes to your serialized save data?

Discussion in 'Scripting' started by DarkCSFixer, Oct 20, 2017.

  1. DarkCSFixer

    DarkCSFixer

    Joined:
    Feb 24, 2017
    Posts:
    19
    I'm making save data for a game that I plan on updating a lot. There may be some save data information added and taken away over the upcoming months, so I wanted to make sure I had a way to update the game's save data. I figured I would do this by adding an update code. If the update code in the game is higher then the one in the save data then it simply updates the information.

    So the problem becomes how do add an update code to the save data separate from the main serialized data. If it unpacks all the data then it gets an error since stuff is missing. So I thought about adding a second class, so one would hold all the information and the other would hold the update code. That way I could take out just the update code, and if everything looks alright take out the rest. But... How do you do that?

    This is the code I'm using right now to load information.

    Code (CSharp):
    1. BinaryFormatter bf = new BinaryFormatter();
    2.             FileStream file = File.Open(Application.dataPath + "/SAVE/savedata.moewars", FileMode.Open);
    3.             FileData data = (FileData)bf.Deserialize(file);
    4.             file.Close();
    Or maybe there's a way to just unpack only the update code instead of unpacking all of it? That could maybe work if someone knows how to do that.
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    What you're asking for is a lot easier to do if you're using a text-based format (JSON, YAML) than binary. Those formats handle missing data just fine.

    Binary formatting works (pretty much) by putting in the bytes in the correct order, so just getting some of the data means finding the correct offset the bytes are at, and interpreting that correctly. I don't think that's possible with the default formatter, and it'd be a lot of work! If you want to stick to binary serialization, you'll need to keep a class containing all of the fields of the old version around, so you can first deserialize into that, and then copy from that into a new version.

    I'd only recommend binary save data if you're creating very large save files. Even if you're planning on using binary data in the end, it can be smart to use eg. json while developing, and then change back to binary once the save data stops changing.
     
  3. DarkCSFixer

    DarkCSFixer

    Joined:
    Feb 24, 2017
    Posts:
    19
    I don't know if that would work. I heard that JSON is really easy to edit. The game is going to be an free RPG type game with paid DLCs. So I don't want it to be super easy for someone to edit the save data.