반응형
Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Do Something IT

[Unity] xml 사용 본문

Unity3D

[Unity] xml 사용

아낙시만더 2013. 9. 25. 12:15
반응형


this post shows a simple tutorial to do some basic operations with xml file on Unity3D using C#.

How to load?

Put an XML file on Resources folder and load it with Resources class from Unity3D
xml sample:

<achievement>
 <uniqueid>0</uniqueid>
 <referencename>My Achievement</referencename>
 <goal>Solve until 10 seconds</goal>
 <points>10</points>
</achievement>

using UnityEngine;
using System.Collections;
using System.Xml;


public class XMLEditor : MonoBehaviour
{

    void Awake()
    {
        //Load
        TextAsset textXML = (TextAsset)Resources.Load("myxml.xml", typeof(TextAsset));
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(textXML.text);
    }
}
Yeah! Using a TextAsset you can make it very simply!

How to read?

Pretty simple! Use .NET framework, XmlDocument will turn you live more easy.

using UnityEngine;
using System.Collections;
using System.Xml;


public class XMLEditor : MonoBehaviour
{
    void Awake()
    {
        //Load
        TextAsset textXML = (TextAsset)Resources.Load("myxml.xml", typeof(TextAsset));
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(textXML.text);

        //Read
        XmlNode root = xml.FirstChild;
        foreach(XmlNode node in root.ChildNodes)
        {
            if (node.FirstChild.NodeType == XmlNodeType.Text)
                Debug.Log(node.InnerText);
        }
    }
}

Ok, but if there are multiple hierarchies you will must implement your own ReadMethod to do that by navigating for all nodes.

How to save?

using UnityEngine;
using System.Collections;
using System.Xml;


public class XMLEditor : MonoBehaviour
{
    void Awake()
    {
        //Load
        TextAsset textXML = (TextAsset)Resources.Load("myxml.xml", typeof(TextAsset));
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(textXML.text);

        //Read
        XmlNode root = xml.FirstChild;
        foreach(XmlNode node in root.ChildNodes)
        {
            if (node.FirstChild.NodeType == XmlNodeType.Text)
                node.InnerText = "none";
        }

        //Simple Save
        xml.Save(AssetDatabase.GetAssetPath(textXML));
    }
}
The easy way! :)

참조 : 바로가기


반응형
Comments