您的位置:首页 > 移动开发 > Unity3D

Unity——读取xml文件生成一级树形菜单

2017-04-24 10:31 330 查看
从毕业到工作,经过多个项目的历练,我的编程能力可以说已经经历了从菜鸟到小有所成的状态。在这个互联网的时代,在网上常常能够看到各种编程大牛写的一些关于自己编程中的经验知识点。

很多时候,看着他们的文章,总会觉得,自己也成为一名程序员许多年了,就算没有一些特别新颖,高超的技术能力,但是在做过的项目中,也是常常会遇到各式各样的问题,或者一些比较实用的方法之类的东西。所以在此,我会记录下来自己在编程岁月里的点点滴滴,也让自己觉得多年的工作还是有所收获的。

今天,我想介绍一下在做Unity项目中所使用的一个树形菜单。 树形菜单可以说是一个比较常用的导航形式,无论是windows中的文件夹、或者是一些视频网站、社交网站中都会使用到这种菜单形式。

首先,因为我希望树形菜单能够编辑的更加灵活,所以我将树形菜单的内容都存储在xml文件内,通过读取xml里的内容,来动态创建树形菜单的各个节点。

我将xml文件放在Resources目录下,所以取文件的路径我定义为:

private string path = UnityEngine.Application.dataPath + "/Resources/";

      注:需要注意的是,通过Resources读取文件的时候是不需要加后缀名的。

xml文件内容如下:

      这里,我使用的NGUI插件,先创建树节点预置物。

最后,编写好创建树的代码,将其挂在主相机上,并运行,就能生成树形菜单。

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

public class main : MonoBehaviour {

public string filename;
private string path = UnityEngine.Application.dataPath + "/Resources/";
public GameObject UIRoot;

// Use this for initialization
void Start () {
LoadXmlCreateTree("tree");
}

// Update is called once per frame
void Update () {

}

private void LoadXmlCreateTree(string name)
{
#region //读取xml文件

XmlDocument treeXml = new XmlDocument();
TextAsset textAsset = (TextAsset)Resources.Load(path+name, typeof(TextAsset));
if (textAsset == null)
Debug.Log(path + name);
treeXml.LoadXml(textAsset.text);

#endregion

#region //生成树

GameObject treeNode = (GameObject)Resources.Load("node");
treeNode = Instantiate(treeNode);
XmlNodeList xmlNodeList = treeXml.SelectSingleNode("root").ChildNodes;
foreach (XmlElement xl1 in xmlNodeList)
{
treeNode.transform.GetChild(0).GetComponent<UILabel>().text = xl1.GetAttribute("name");
treeNode.transform.parent = UIRoot.transform;
treeNode.transform.localPosition = new Vector3(-300, 200, 0);
treeNode.transform.localScale = new Vector3(1, 1, 1);
if (xl1.HasChildNodes)
{
int i = 1;
foreach (XmlElement xl2 in xl1)
{
GameObject childNode = (GameObject)Resources.Load("node");
childNode = Instantiate(childNode);
childNode.transform.GetChild(0).GetComponent<UILabel>().text = xl2.GetAttribute("name");
childNode.transform.parent = treeNode.transform;
childNode.transform.localPosition = new Vector3(50, -50*i, 0);
childNode.transform.localScale = new Vector3(1, 1, 1);
i++;
}
}
}
#endregion
}
}


效果展示:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity tree xml