1

What happens when I cast an object to a class and the object does not have a variable that I have in my class? In the below example, I am loading from a FileStream which I serialized from a PlayerData before. However at the time of the serializing there was no score variable included in PlayerData, so the file does not contain that. If I load like below, what happens to the score variable? Is there a way to set the value to zero whenever a situation like this arises ?

public string userID;
public bool userCreated;
public double score;

     public void Load () {

            if (File.Exists (Application.persistentDataPath + "/SaveGame.dat")) {

                Debug.Log ("Loading from local space");

                BinaryFormatter bf = new BinaryFormatter ();
                FileStream file = File.Open (Application.persistentDataPath + "/SaveGame.dat", FileMode.Open);
                PlayerData data = (PlayerData) bf.Deserialize (file); // Question pertains this step
                file.Close ();
                userID = data.userID;
                userCreated = data.userCreated;
                score = data.score;
            }
    }
 [System.Serializable]
 class PlayerData {

     public string userID;
     public bool userCreated;
     public double score;
 }
Doruk Okbay
  • 111
  • 4
  • 1
    Not sure about Unity, but in .Net you need to mark `score` with `[OptionalField]`. See: [Deserializing a newer version of an object from an older version of the object](https://stackoverflow.com/a/19718498/3744182). `0` is the default value for a double so you don't need to initialize it, but if you did you could do it in an `[OnDeserializing]` method, see [Field Initializer in C# Class not Run when Deserializing](https://stackoverflow.com/a/9419943/3744182). In fact I think this is a duplicate of those two, agree? – dbc Feb 06 '20 at 19:42
  • See also https://learn.microsoft.com/en-us/dotnet/standard/serialization/version-tolerant-serialization – dbc Feb 06 '20 at 19:45
  • 1
    Thank you so much! Yes, it is the same question. – Doruk Okbay Feb 06 '20 at 19:49

1 Answers1

0

If I remember correctly, it will be set to its default value. For numbers it is 0