- Home /
Questions about XML serialization of Class Properties
I am currently teaching myself how to save data through C# in Unity using methods other than PlayerPrefs. I decided to start with XML. I first tried to serialiaze a number of properties within my TimeController class, which inherited from Monobehaviour. I then learned that you cannot serialize classes that inherit from monobehaviour. I then created a separate class to read the properties of the original class (TimeSaveData) that doesn't inherit from monobehaviour. I then learned that you cannot serialize a class that has a public constructor, so I removed the TimeSaveData class' public constructor and assigned the values of the properties manually
I now have the following approach:
//original class
public class TimeController : MonoBehaviour
{
//the properties I want to save
public int igCurrentTime{get; set;}
public int igTotalNumDaysPassed {get; set;}
public int rwTimeOfSave{get; set;}
public void SaveTimes()
{
//read real world time in minutes
rwTimeOfSave = DateTime.Now.Minute;
//Instance the TimeSaveData class and transfer the values of all properties
TimeSaveData saveData = new TimeSaveData();
saveData.igCurrentTime = igCurrentTime;
saveData.igTotalNumDaysPassed = igTotalNumDaysPassed;
saveData.rwTimeOfSave = rwTimeOfSave;
//I have a seperate class with a generic method for creating XML save files
SaveLoad.SaveFile(Path.DirectorySeparatorChar + this.ToString(), saveData);
}
}
//Class created as a holder for all the properties I want to serialize
[XmlRoot]
public class TimeSaveData
{
[XmlElement]
public int igCurrentTime{get; set;}
[XmlElement]
public int igTotalNumDaysPassed {get; set;}
[XmlElement]
public int rwTimeOfSave{get; set;}
}
This seems like a cumbersome way of saving data. Am I approaching XML serialization the wrong way, or is the inability to serialize properties from classes that inherit from Monobehaviour just something that is accepted? If so, are there any better/more efficient methods for me to do what I'm trying to do?
Thanks for any responses in advance.
Matt
Answer by vuwij · Oct 28, 2016 at 07:51 AM
Use the DataContractSerializer instead https://msdn.microsoft.com/en-us/library/6exf3h2k(v=vs.110).aspx According to this page, DataContractSerializer is better than XmlSerializer as it doesn't run into as many problems as XML serialization