- Home /
Loading a serialized file after changing the adding a new var to it
Hi,
I'm loading all the data of my game using
SaveVariables.current = (SaveVariables)bf.Deserialize(file);
But I have to add a new variable to SaveVariables, like that :
using UnityEngine;
using System.Collections;
[System.Serializable]
public class SaveVariables
{
public static SaveVariables current;
public int c = 500;
public bool[] m = new bool[4];
public bool[] md = new bool[4];
public bool[] p = new bool[5];
public bool[] pd = new bool[5];
public int roundsPlayed = 0;
public int gamesPlayed = 0;
public int bulletsShot = 0;
public int grenadesShot = 0;
public int lazersShot = 0;
public int bouncyShot = 0;
public int playersDead = 0;
public int powerupsDestroyed = 0;
public bool sound = false;
public int ad = 0;
public string adTime = "";
public bool rated = false;
public string newVar = ""; // NEW VARIABLE
}
After adding the new var, I'm getting an error because an error because this newVar don't exists in the save file How can I fix that ?
I created a class with few public members and used BinaryFormatter to save an instance of this class into a file, then added some more public members to the class and used BinaryFormatter's Deserialize without any issue (the members missing from file were assigned with the default value of their type [of course not with the "default" you set in the class], for example a string member was set to an empty string).
Can you paste here the exception you're getting? Because it's strange that deserialization fails with only missing members (you should have issues if you change or delete a member that is ins$$anonymous$$d stored in the file).
Answer by hexagonius · Sep 27, 2018 at 08:43 AM
Check out the OptionalFieldAttribute. it's basically what you need. it lets you change the class, adding in new fields marked with this attribute so they will be defaulted on deserialization of data that do not contain them, not throwing errors.
https://docs.microsoft.com/en-us/dotnet/standard/serialization/version-tolerant-serialization#tolerance-of-missing-data
Answer by DownER149 · Sep 26, 2018 at 03:54 PM
i doubt its possible. just output your files as plan text until your ready to publish