using System.Collections.Generic; using UnityEngine; using System.Xml; public class ConfigManager : Manager { private Dictionary<string, object> configs; public override void Init() { //获取到Resources/Config下的所有配置文件 并且解析 configs = new Dictionary<string, object>(); TextAsset[] textAsset = Resources.LoadAll<TextAsset>("Config"); for(int i =0;i<textAsset.Length;i++) { AnalysisConfig(textAsset[i]); Resources.UnloadAsset(textAsset[i]); } GameManager.Instance.DebugManager.Logic.Log("配置管理器初始化完成!"); } //加载解析xml配置 private bool AnalysisConfig(TextAsset file) { XmlDocument xml = new XmlDocument(); xml.LoadXml(file.text); XmlNode parent = xml.FirstChild; string FileKey = file.name; if (configs.ContainsKey(FileKey)){ GameManager.Instance.DebugManager.Error.Log("配置文件名不能重复!"); return false; } Dictionary<string, object> FileNode = new Dictionary<string, object>(); FileNode = ParseNode(parent) as Dictionary<string,object>; configs.Add(FileKey, FileNode); return true; } private object ParseNode(XmlNode node) { object newNode = new object(); XmlNodeList list = node.ChildNodes; if (list.Count > 0 && list[0].Name != "#text") { //数组 Dictionary<string, object> dic = new Dictionary<string, object>(); foreach (XmlNode cNode in list) { object ccNode = new object(); ccNode = ParseNode(cNode); if (dic.ContainsKey(cNode.Name)) { GameManager.Instance.DebugManager.Error.Log(string.Format("同一个父节点下的子节点的标签名不能相同:{0}", cNode.ParentNode.Name + cNode.Name)); return null; } dic.Add(cNode.Name, ccNode); } newNode = dic; } else { //单元素数据 退出点 newNode = node.InnerText; } return newNode; } /// <summary> /// 格式:配置文件名.根节点下的子节点.根节点下的子节点的子节点 /// 注意不需要写根节点的标签名 public T GetConfigByKey<T>(string key) { string[] keys = key.Split('.'); if (!configs.ContainsKey(keys[0])) { GameManager.Instance.DebugManager.Error.Log(string.Format("缺少{0}的配置文件", keys[0])); return default(T); } Dictionary<string, object> dic = configs[keys[0]] as Dictionary<string, object>; object TargetNode = dic; for (int i = 1; i < keys.Length; i++) { dic = TargetNode as Dictionary<string, object>;//往前推进 if (!dic.ContainsKey(keys[i])) { GameManager.Instance.DebugManager.Error.Log(string.Format("缺少{0}节点", keys[i])); return default(T); } TargetNode = dic[keys[i]]; } return (T)TargetNode; } }
启动的时候,将指定Resources/Config目录的配置文件一并解析到内存中,通过key的方式获取到配置信息
需要添加配置,只需要在Resources/Config目录下创建配置文件就行了,自己再根据格式获取到配置,用于一些不用经常修改的、轻量的配置
如果是一些需要经常修改,重量的,使用网络AssetBundle加载。
思路:来自于php laravel的配置