So i have made XML writer.
It has this class to define how XML file looks like:
public class GameFeaturesXML
{
[XmlElement("Name")]
public string name;
[XmlElement("FeatureType")]
public List<int> featureType;
}
(i reduced amount of items for this question)
and reading it works just fine BUT when i want to write List from my program to this XML element (featureType) or when i try to access featureType list to see its contents or even just check with count if anything is in there i just get NullReferenceException.
where problem could maybe be is how i create variable maybe?
i create one instance of that file like this:
GameFeaturesData GFD = new GameFeaturesData();
where game features data is this class:
[XmlRoot("Database")]
public class GameFeaturesData
{
[XmlArray("GameFeatures")]
[XmlArrayItem("Feature")]
public List<GameFeaturesXML> gameFeatures = new List<GameFeaturesXML>(); //Creates list of previous Class
public static GameFeaturesData Import(string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(GameFeaturesData));
FileStream stream = new FileStream(path, FileMode.Open);
GameFeaturesData gameFeaturesData = serializer.Deserialize(stream) as GameFeaturesData;
stream.Close();
return gameFeaturesData;
}
public void Save(string path, GameFeaturesData data)
{
XmlSerializer serializer = new XmlSerializer(typeof(GameFeaturesData));
FileStream stream = new FileStream(path, FileMode.Create);
serializer.Serialize(stream, data);
stream.Close();
}
}
You don’t need the blocks. Just make sure your classes are [System.Serializeable] and save and load the class. The Lists will be save and loaded at dynamic sizes.
Here’s an example of the output XML file for an XMLSerialize example project I often share:
Class:
[System.Serializable]
public class Player
{
public string name = "Test Drive Dummy";
public int health = 100;
[SerializeField]public List<Guns.Pistol> pistols; //Lists aren't serialized by default, so we have to mark them for serialization with [SerializeField]
[SerializeField]public List<Guns.Gattling> gattlingGuns;
[SerializeField]public List<Animals.Animal> animals;
}
could you please also also show Guns.Pistol class or any other from which list is formed. dont quite understand Guns. part but i think Pistol class is something like:
public class Pistol
{
string name;
...
}
do you still need to use [XmlElement] for name field in Pistol class?
in short could you please post like entire example?
Sorry my mistake, been on some all night crunches this week and got the posts mixed up. Yeah to actually save to XML you don’t need the [System.Serializeable] above the class, but if you want Unity to show it in the Inspector you do, which most people would want out of their player class.