Unity中xml配置表管理器
发表于2019-01-25
本篇内容主要给大家分享下在Unity开发者中xml配置表管理器的使用,核心思想是使用反射把配置表中的数值赋给对象的属性。
直接上代码,代码里有比较详细的注释:
public static List<T> Load<T>() where T : new(){
//这里要注意配置对象要与配置文件名称相同
string[] names = (typeof(T)).ToString().Split('.');
//获取真实名称
string filename = names[names.Length - 1];
XmlDocument doc = new XmlDocument();
//加载xml文件
string data = Resources.Load("Config/"+filename).ToString();
doc.LoadXml(data);
XmlNode xmlNode = doc.DocumentElement;
XmlNodeList xnl = xmlNode.ChildNodes;
List<T> ret = new List<T>();
//遍历所有内容
foreach (XmlNode xn in xnl)
{
//找到符合条件的数据
if (xn.Name.ToLower() == filename)
{
//实例化数据对象
T obj = new T();
Type t = obj.GetType();
//获取对象的全部属性
FieldInfo[] fields = t.GetFields();
string msg = "";
try{
//遍历全部属性,并从配置表中找出对应字段的数据并赋值
//根据属性的类型对数据进行转换
foreach (FieldInfo field in fields){
if(xn.Attributes[field.Name] == null){
Debug.Log("the field [" + field.Name + "] is null !!!");
continue;
}
string val = xn.Attributes[field.Name].Value;
if(val == null){
Debug.Log("the field [" + field.Name + "] is null !!!" );
continue;
}
msg = field.Name + " : "+ val + " type : " + field.FieldType;
if (field.FieldType == typeof(int))
{
field.SetValue(obj, int.Parse(val));
}
else if (field.FieldType == typeof(float))
{
field.SetValue(obj, float.Parse(val));
}
else if (field.FieldType == typeof(string))
{
field.SetValue(obj, val);
}
}
ret.Add(obj);
}catch(Exception e){
Debug.LogError("=====================" + filename + "==================");
Debug.LogError(e.Message);
Debug.LogError(msg);
}
}
}
return ret;
}
使用方法
现在有这样一张配置表:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <role_confs> <role_conf id="20003" name="box3" description="啊啊啊" file_path="Box003" unlock_type="-1" unlock_price="200" /> <role_conf id="20004" name="box4" description="啊啊啊" file_path="Box004" unlock_type="1" unlock_price="200" /> <role_conf id="20005" name="box5" description="啊啊啊" file_path="Box005" unlock_type="1" unlock_price="200" /> <role_conf id="20006" name="box6" description="啊啊啊" file_path="Box006" unlock_type="1" unlock_price="200" /> </role_confs>
首先定义数据类,注意数据类的名称要与配置表文件一致,则对应的数据类应该是这样的:
public class role_conf
{
public int id;
public string name;
public string description;
public string file_path;
public int unlock_type;
public int unlock_price;
}
加载数据:
List<role_conf> _datas = Load<role_conf>();
这样,xml表中的每一个数据就对应list中的一个对象了。
