Last active
September 17, 2015 09:37
-
-
Save Talsidor/42df07fc4f9d286f891b to your computer and use it in GitHub Desktop.
Quick and Easy C# Object <> XML Serialization/Deserialization in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
/// <summary> | |
/// Quick and easy C#<>XML (de)serialization example by @Talsidor | |
/// References: | |
/// https://stackoverflow.com/questions/4123590/serialize-an-object-to-xml | |
/// https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document | |
/// </summary> | |
public class ObjectSerialization : MonoBehaviour | |
{ | |
public Car[] cars; | |
void Start() | |
{ | |
// Comment in whichever of these lines you wish to happen | |
//Car.Deserialize("cars"); | |
Car.Serialize("cars"); | |
// Publicly visible in the Unity inspector so you can see the contents of the Car.cars array | |
cars = Car.cars; | |
} | |
} | |
[System.Serializable] | |
public class Car | |
{ | |
public static Car[] cars; | |
// The information contained in one instance of this class | |
public string make; | |
public string model; | |
public int year; | |
/// <summary> | |
/// Turns the 'cars' array into an XML file with the specified filename | |
/// </summary> | |
/// <param name="fileName">Adds dataPath and extension automatically</param> | |
public static void Serialize (string fileName) | |
{ | |
// Populate with example data so we have something to serialize | |
cars = new Car[] { | |
new Car() { make = "Toyota", model = "Prius", year = 2013 }, | |
new Car() { make = "Mitsubishi", model = "iMiev", year = 2012 }, | |
new Car() { make = "Tesla", model = "Model S", year = 2014 } | |
}; | |
using (var writer = new System.IO.StreamWriter(Application.dataPath + "/" + fileName + ".xml")) | |
{ | |
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Car[])); | |
serializer.Serialize(writer, cars); | |
} | |
} | |
/// <summary> | |
/// Retrives the specified file and populates the 'cars' array with it's contents | |
/// </summary> | |
/// <param name="fileName">Adds dataPath and extension automatically</param> | |
public static void Deserialize(string fileName) | |
{ | |
using (var stream = System.IO.File.OpenRead(Application.dataPath + "/" + fileName + ".xml")) | |
{ | |
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Car[])); | |
cars = serializer.Deserialize(stream) as Car[]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Creates an XML file that looks like: