Keeping data with different version of save files

Let’s say I’m saving the current stats of my player’s health as a float in the save data. After some updates to my game I’ve decided to round up the values and now everything is stored as ints.

How could I deserialize it while not losing any of the previous save data?

This is a tricky issue, and ultimately the best solution is to plan your data ahead and not need to version your save files. That being said, there is a solution to the problem.
Let’s take your example, substituting an int for a float in the save file.
Your normal RestoreState looks like this:

public void RestoreState(object state)
{
    currentHealth= (float)state;
}

As currentHealth is a float, this should work perfectly fine. If, however, we switch currentHealth to an int, you’ll get an error that state cannot be cast to an int if the last save was a float.

Here’s what you can do to make this work, assuming that currentHealth is now an integer value:

public void RestoreState(object state)
{
     if(state is int integerValue)
     {
          currentHealth=integerValue;
     }
     else if (stat is float floatValue)
     {
          currentHealth = Mathf.FloorToInt(floatValue);
     }
}

The is keyword can be used to test a cast… it’s functionally equivalent to a try/catch block. If the test fails, then we test to make sure that the value is a float, and then cast that to an int.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms