Unity - XML

From NoskeWiki
Jump to: navigation, search


NOTE: This page is a daughter page of: Unity

Unity / Unity3D is a multi-platform 3D game engine and on this page I was hoping to collect snippets of code showing how you can save data and load data from XML files using Unity. Sadly I only have one example so far! All code will be in C#, as C# is the most powerful language to code Unity games, and also the one with the best XML support.

How to use XML within Unity3D

Unity3D uses the Mono implementation of the .net XML processor. And yes, this should work on Mac as well as Windows machines. This means the first thing you'll have to include "using Systems.Xml" (see: Systems.XML) ]in your include list and in order to open files and process strings you'll also need to include "using Systems.IO". A simple example showing how to load XML from a string is below:

using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
public class XmlExample
  public XmlExample()
        <title>The Art of the Start</title><author><last-name>Kawasaki</last-name></author>
        <title>Real Estate Mistakes</title><author><last-name>Jenman</last-name></author>
  //-- Prints out all "titles" in the "xmlData" string provided
  public void printTitlesInXMLString(string xmlData)
    XmlDocument doc = new XmlDocument();
    doc.Load(new StringReader(xmlData));
    XmlNodeList elemList = doc.GetElementsByTagName("title");
    for (int i=0; i < elemList.Count; i++)
      Debug.Log(elemList[i].InnerXml);  // Will print out "The Art of the Start" and "Real Estate Mistakes".

Articles about using XML within Unity3D

  • XML and Unity3D - a great article showing how to use XML, but may be broken link now... doh!
  • Reading text data into a unity game - doesn't talk about XML, but explains the three different methods (loading from resource, loading from file, loading from web)
  • Loading an XML file - unity community forum thread where people discuss the use of writing their own XML parses to keep file size down.

Other Pages