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.