天天看点

Unity中用代码保存多个位置信息并生成XML

创建几个空物体当作需要保存位置信息的物体

Unity中用代码保存多个位置信息并生成XML

代码块:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEngine;

public class Test : MonoBehaviour
{
    public List<Transform> posLst = new List<Transform>();
    
    public void Start()
    {
        FileInfo fi = new FileInfo(Application.dataPath + "test.xml");
        if (fi.Exists)
        {
            fi.Delete();
        }
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("Pos");//根节点
        for (int i = 0; i < posLst.Count; i++)
        {
            XmlElement pos = doc.CreateElement("Pos");//
            XmlElement name = doc.CreateElement("Name");
            XmlElement x = doc.CreateElement("X");
            XmlElement y = doc.CreateElement("Y");
            pos.SetAttribute("ID",(i+1).ToString());
            name.InnerText = posLst[i].gameObject.name;
            x.InnerText = (posLst[i].position.x).ToString();
            y.InnerText = (posLst[i].position.y).ToString();

            doc.AppendChild(root);
            root.AppendChild(pos);
            pos.AppendChild(name);
            pos.AppendChild(x);
            pos.AppendChild(y);
        }
        doc.Save(Application.dataPath +"test.xml");
    }
}

           

最后生成的XML

Unity中用代码保存多个位置信息并生成XML