首页 > 技术文章 > Unity XML的使用

Fflyqaq 原文

目录

C#中的XML

XML文档对象模型(DOM)是C#里一种很直观的方式处理XML的类,在System.Xml命名空间中。

常用的DOM类

XML开发实例

在实际开发中,各种的配置数据肯定都是策划决定的。就比如每个关卡的名字,完成关卡后获得的金钱和经验。而微软的Excel可以一键转换为XML,所以策划可以直接把数据写在Excel中,转换为XML就可以直接把信息加载保存到游戏中。

XML代码

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<item ID="10001">
		<sceneName>01SceneGame</sceneName>
		<playerBornPos>-10,12.3,11.5</playerBornPos>
		<playerBornRote>0,145,0</playerBornRote>
		<exp>1250</exp>
		<coin>980</coin>
	</item>
	<item ID="10002">
		<sceneName>02SceneGame</sceneName>
		<playerBornPos>-10,13.2,11.5</playerBornPos>
		<playerBornRote>0,145,0</playerBornRote>
		<exp>1350</exp>
		<coin>1080</coin>
	</item>
</root>

C#中对应的类

public class MapData
{
public int id; //场景名 public string sceneName; //角色初始出生位置和方向 public Vector3 playerBornPos; public Vector3 playerBornRote;   //通关后获得的金币和经验 public int coin; public int exp; }

  

读取XML信息到字典

    /// <summary>
    /// 保存地图信息的字典
    /// </summary>    
    private Dictionary<int, MapData> mapDataDict = new Dictionary<int, MapData>();

    /// <summary>
    /// 初始化地图信息
    /// </summary>
    /// <param name="path">XML文件位置</param>
    private void InitMapXML(string path)
    {
        TextAsset nameText = Resources.Load<TextAsset>(path);
        if (nameText == null)
        {
            Debug.Log("xml file:" + path + "not exist", LogType.Error);
        }
        else
        {
//声明一个XmlDocement对象,加载XML文件 XmlDocument doc = new XmlDocument(); doc.LoadXml(nameText.text); //获取root下的所有节点 XmlNodeList nodeList = doc.SelectSingleNode("root").ChildNodes; for (int i = 0; i < nodeList.Count; i++) { XmlElement element = nodeList[i] as XmlElement; if (element.GetAttributeNode("ID") == null) continue; int id = Convert.ToInt32(element.GetAttributeNode("ID").InnerText);
//每个节点下所有数据转换为一个MapData类 MapData mapData = new MapData { ID = id, }; foreach (XmlElement ele in nodeList[i].ChildNodes) { switch (ele.Name) { case "sceneName": mapData.sceneName = ele.InnerText; break; case "playerBornPos": { string[] temp = ele.InnerText.Split(','); mapData.playerBornPos = new Vector3(float.Parse(temp[0]), float.Parse(temp[1]), float.Parse(temp[2])); } break; case "playerBornRote": { string[] temp = ele.InnerText.Split(','); mapData.playerBornRote = new Vector3(float.Parse(temp[0]), float.Parse(temp[1]), float.Parse(temp[2])); } break; case "coin": mapData.coin = int.Parse(ele.InnerText); break; case "exp": mapData.exp = int.Parse(ele.InnerText); break; } } mapDataDict.Add(id, mapData); } } } /// <summary> /// 根据id获取对应数据 /// </summary> public MapData GetMapData(int id) { MapData data = null; mapDataDict.TryGetValue(id, out data); return data; }

  

推荐阅读