实现鼠标放在某一个物体上显示物体的名称或者其他信息,用xml储存名称等信息,鼠标触碰时触发条件
附上代码比较垃圾,但是可以使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;
using UnityEngine.UI;
using System;
public class xmltest : MonoBehaviour {
string id1;
public string name1;
public Text textname;
public Camera maincam;
//xml文件位置
public string filePath;
RaycastHit hit;
public bool bhit = false;
Dictionary<int, string> dicxml;
public int dicindex = 0;
XmlNodeList node;
XmlDocument xmlDoc;
private void Start()
{
parseXml();
}
private void Update()
{
getcode();
}
//解析xml
void parseXml()
{
dicxml = new Dictionary<int, string>();
filePath = Application.dataPath + "/Resources/item.xml";
if (File.Exists(filePath))
{
xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
node = xmlDoc.SelectSingleNode("item").ChildNodes;
//也可以前面加上@,区别就是有@的话,双引号里面的内容不转义,比如" \" "
for (int i = 0; i < node.Count; i++)
{
dicxml.Add(dicindex++, node[i].Name);
}
}
}
void getcode()
{
Ray ray = maincam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (dicxml.ContainsValue(hit.collider.name))
{
XmlElement xmlElem = xmlDoc.DocumentElement;//获取根节点
XmlNodeList xnl = xmlElem.GetElementsByTagName(hit.collider.name);//取节点名
for (int i = 0; i < xnl.Count; i++)
{
foreach (XmlElement i1 in xnl[i].ChildNodes)
{
bhit = true;
if (i1.Name == "name")
{
name1 = i1.InnerText;
textname.text = i1.InnerText;
}
if (i1.Name == "id")
{
}
}
}
}
else
{
bhit = false;
}
}
}
void OnGUI()
{
try
{
if (bhit==true )
{
GUI.skin.box.fontSize = 12;
GUI.Box(new Rect(Input.mousePosition.x, Screen.height - Input.mousePosition.y - 10, 100, 25), textname.text);
}
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
}