首页 > 代码库 > 保存物体下的子物体信息到Xml 里面
保存物体下的子物体信息到Xml 里面
<新手上路>(保存物体下的子物体信息到Xml 里面)
2016-12-20
根据个人特殊需要所写
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using UnityEditor;
public class SaveMapCtr
{
[MenuItem("Tools/Creat MapInfo")]
public static void CreatMapInfo()
{
//选中的物体
Transform tParent=((GameObject)Selection.activeObject).transform;
XmlDocument xml = CreatXml();
//遍历所选择物体下的子物体 子物体名作为ID名保存到节点下
foreach (Transform item in tParent)
{
//添加根节点
AddNodeXml(xml, item.name);
//添加子节点
GetRootSetObj(xml, item);
}
SaveXML(xml);
}
//根据物体名 进行分割 区分物体名 和预制物名 和位置参数
public static void GetRootSetObj(XmlDocument xml,Transform root)
{
foreach (Transform item in root)
{
string[] SliptName = DivisionStr(item.name);
AddNodeChildXml(xml, root.name,item.name,SliptName[0], item.transform.position, item.transform.localEulerAngles, item.transform.localScale);
}
}
//创建节点
public static XmlDocument CreatXml()
{
string filepath = Application.dataPath + "/MapInfoXml.xml";
//判断当前路径下是否有该文件 如果存在就删除重新创建
if (File.Exists(filepath))
{
File.Delete(filepath);
}
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("Root"));
return xml;
}
//添加根节点
public static void AddNodeXml(XmlDocument xml, string id)
{
//获取根节点
XmlNode root = xml.SelectSingleNode("Root");
//添加元素
XmlElement element = xml.CreateElement("Scene");
element.SetAttribute("Id", id);
root.AppendChild(element);
}
//添加子节点
public static void AddNodeChildXml(XmlDocument xml, string id, string objName, string prefabName, Vector3 pos, Vector3 rotate, Vector3 scal)
{
XmlNode root = xml.SelectSingleNode("Root");
foreach (XmlElement element in root)
{
if (element.GetAttribute("Id") == id)
{
//在Node节点下添加子节点
XmlElement titleElelment = xml.CreateElement("object");
titleElelment.InnerText = objName + "," + prefabName + "," + pos.x.ToString() + "," + pos.y.ToString() + "," + pos.z.ToString()+","+ rotate.x.ToString() + "," + rotate.y.ToString() + "," + rotate.z.ToString() +","+ scal.x.ToString() + "," + scal.y.ToString() + "," + scal.z.ToString();
element.AppendChild(titleElelment);
root.AppendChild(element);
}
}
}
public static void SaveXML(XmlDocument xml)
{
//存储xml文件
xml.Save(Application.dataPath + "/MapInfoXml.xml");
}
//根据分号来分割字符串
public static string[] DivisionStr(string str)
{
return str.Split(‘_‘);
}
}
保存物体下的子物体信息到Xml 里面