- Home /
C# Saving Values to XML
Hi Everyone, I was wondering how would you save Values from a script to XML? I have the values setup in my script but I don't know how to save them to XML. Any help would be appreciated.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ExampleScript : MonoBehaviour{
public int ExampleInt;
public bool ExampleBool;
public float ExampleFloat;
public string ExampleString;
public int[] ExampleArray;
public List<string> ExampleList = new List<string>();
//What comes next?
}
Edit: I decided to go with the XML serialization tutorial at switchonthecode and tried to adapt it to my own code.However I have encountered this error no overload for SerializeToXML takes 0 arguments.I'm not sure what argument I want to put in that call. Also do you see any other problems within my code?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public class ExampleScript : MonoBehaviour{
public int ExampleInt;
public bool ExampleBool;
public float ExampleFloat;
public string ExampleString;
public int[] ExampleArray;
public List<string> ExampleList = new List<string>();
}
public class ExampleScriptSave: ExampleScript{
[XmlElement("exampleArray")]
public int[] exampleArray {
get {
return this.ExampleArray;
}
set {
ExampleArray = value;
}
}
[XmlElement("exampleBool")]
public bool exampleBool {
get {
return this.ExampleBool;
}
set {
ExampleBool = value;
}
}
[XmlElement("exampleFloat")]
public float exampleFloat {
get {
return this.ExampleFloat;
}
set {
ExampleFloat = value;
}
}
[XmlElement("exampleInt")]
public int exampleInt {
get {
return this.ExampleInt;
}
set {
ExampleInt = value;
}
}
[XmlElement("exampleList")]
public List<string> exampleList {
get {
return this.ExampleList;
}
set {
ExampleList = value;
}
}
[XmlElement("exampleString")]
public string exampleString {
get {
return this.ExampleString;
}
set {
ExampleString = value;
}
}
static public void SerializeToXML(ExampleScriptSave exampleScriptSave)
{
XmlSerializer serializer = new XmlSerializer(typeof(ExampleScriptSave));
TextWriter textWriter = new StreamWriter(@"C:\exampleScriptSave.xml");
serializer.Serialize(textWriter, exampleScriptSave);
textWriter.Close();
}
void OnGUI(){
if(GUILayout.Button("Save")){
// no overload for method SerializeToXML takes 0 arguments
SerializeToXML();
}
}
}
just FYI it's possible the amazing (free) Unity Serializer can help you. google "Unity Serializer Whydoidoit"
Answer by Karsnen_2 · Dec 17, 2012 at 04:40 PM
I would prefer Mike's Unity Serializer. But as you have specifically mentioned about values to XML, this link is the best to get a start with.