Changing the type of an existing field

Discussion and help for Easy Save 3, The Complete Save Game & Data Serializer System for the Unity Engine
Post Reply
eBehbahani
Posts: 2
Joined: Mon Dec 23, 2024 10:02 pm

Changing the type of an existing field

Post by eBehbahani »

Hi,

I have a class with a number of fields that has been saved in previous versions of my app. I refactored the class and have changed the type of one of the fields of the class from an int to an object. When I try loading the save file, it fails due to a FormatException which I expected. I created a custom type for the class so that I could process the field for either case (if it was an int or an object) but I am struggling to get something workable.

Code: Select all

...
case "_propertyName":
	try
	{
		var newType = reader.Read<System.Collections.Generic.List<MyObject>>();
		reader.SetPrivateField("_propertyName", newType , instance);
	}
	catch (Exception e)
	{
		var oldType = reader.Read<System.Collections.Generic.List<int>>();
		var convertedType = oldType .Select(x => new MyObject(x)).ToList();
		reader.SetPrivateField("_propertyName", convertedType , instance);
	} 
	break;
...
What I am expecting from the above code is that if the new property type deserialization fails, then the default type will be used and converted to the new type. The problem seems to be that Read doesn't recover after throwing a FormatException. Is there something I am missing? Is there a way to check the type of a particular field during deserialization and adjust the output before saving?
User avatar
Joel
Moodkie Staff
Posts: 5069
Joined: Wed Nov 07, 2012 10:32 pm

Re: Changing the type of an existing field

Post by Joel »

Hi there,

Your approach doesn't work because you've already tried to read the data, so you can't try to read it a second time because you've already advanced in the file.

In this case you would usually save a version number in the file to indicate what type of data the file is expected to contain and use this to choose how to load rather than using a try/catch.

All the best,
Joel
Joel @ Moodkie Interactive
Purchase Easy Save | Contact | Guides | Docs | Getting started
eBehbahani
Posts: 2
Joined: Mon Dec 23, 2024 10:02 pm

Re: Changing the type of an existing field

Post by eBehbahani »

Got it! Thanks for the tips.
Post Reply