Unity3D-動態讀取配置檔案,載入遊戲物件
private Dictionary<int,T> LoadConfig<T>(string fileName) where T : class,new()
{
Dictionary<int, T> dic = new Dictionary<int, T>();
TextAsset bossCfgInfo = Resources.Load<TextAsset>("Config/" + fileName);
//新建xml文件物件
XmlDocument document = new XmlDocument();
//把字串載入到物件中
document.LoadXml(bossCfgInfo.text);
//獲取根節點
XmlNode rootNode = document.SelectSingleNode("Root");
//獲取根節點的子節點列表
XmlNodeList nodeList = rootNode.ChildNodes;
//遍歷
foreach (XmlNode node in nodeList)
{
//節點 轉 元素型別
XmlElement element = node as XmlElement;
T obj = CreateAndSetValue<T>(element);
dic.Add(int.Parse( element.GetAttribute("ID")), obj);
}
return dic;
}
配置檔案要對應一個公有類,該類中的欄位唯一對應配置檔案中的一組屬性,變數名必須和配置檔案一致!!!