- Home /
Serializing and Deserializing from/to XML inside Resources folder
Hi everyone,
I'm using a XML file to save all data about my levels in the game, and I'd like to include it automatically on build. So I was thinking to store the XML inside the Resources folder.
Fact is, the sample version of the XML serialize and deserialize functions use a filepath and a FileStream to Serialize/Deserialize the XML, while I need something like Resources.Load("leveldata.xml") and... something else to save the data in the same position.
Here's part of the code I'm using to serialize the content I need
string filepath = Application.dataPath + @"/leveldata.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Levels));
FileStream stream = new FileStream(filepath, FileMode.Create);
serializer.Serialize(stream, _ls);
stream.Close();
And here's the code I'm using to deserialize it:
string filepath = Application.dataPath + @"/leveldata.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Levels));
FileStream stream = new FileStream(filepath, FileMode.Open);
levels = serializer.Deserialize(stream) as Levels;
stream.Close();
What should I change to obtain what I'd like? Do you think there would be a better solution to save/load a bunch of levels to a XML file at runtime?
I'd like a cross/platform solution, that's why I'm thinking about the Resources folder.
Thank you for your time! ;)
EDIT: I forgot to mention that I'll be doing the editing from within the editor while using Play, but of course the final multi-platform build will have to access the Resources version of the file in another way, could you please point me to the right direction? Thank you!
Answer by NeatWolf · Feb 27, 2015 at 11:38 PM
I'm currently using:
TextAsset _xml = Resources.Load<TextAsset>("Match3/leveldata");
XmlSerializer serializer = new XmlSerializer(typeof(Levels));
StringReader reader = new StringReader(_xml.ToString());
levels = serializer.Deserialize(reader) as Levels;
reader.Close();
Is there a better way to do it?
I'm also forcing the refresh of the assets on save by using UnityEditor.AssetDatabase.Refresh();
Your answer
Follow this Question
Related Questions
Problem with path in FileStream 2 Answers
Loading XML asset after build 0 Answers
Xml Serialization of "sub classes" 0 Answers
URGENT - Serializing error The type of argument is not primitive 0 Answers
[SAVING] LIST cannot be serialized because it does not have a default public constructor 0 Answers