using System; using System.Collections.Generic; using System.IO; using UnityEngine; public class ConfigManager : ManagerBase<ConfigManager> { private Dictionary<string, object> _cache = new Dictionary<string, object>(); private string _rootPath; protected override void init() { base.init(); _rootPath = Path.Combine(ClientInfo.DataPath, "ConfigDatas"); } public void readConfigs() { totalCount = 0; this.scan(_rootPath); } public T load<T>() where T : class { string type = typeof(T).ToString(); if(_cache.ContainsKey(type)) { T obj = _cache[type] as T; return obj; } return null; } private int totalCount; private void scan(string directory) { try { if (!Directory.Exists(directory)) { Debug.LogError("路径不存在:" + directory); return; } string[] dircs = Directory.GetDirectories(directory); for (int i = 0; i < dircs.Length; i++) { scan(dircs[i]); } string[] filePaths = Directory.GetFiles(directory); for (int i = 0; i < filePaths.Length; i++) { string filePath = filePaths[i]; string extend = Path.GetExtension(filePath); string name = Path.GetFileNameWithoutExtension(filePath); if (!string.Equals(extend , ".json")) continue; string structName = string.Format("{0}Data", name); Type type = Type.GetType(structName); if (type == null) { Debug.LogWarning("没有定义 " + structName); continue; } totalCount++; #if UNITY_EDITOR filePath = filePath.Replace("/", "\\"); #endif filePath = string.Format("file://{0}", filePath); FileTool.Instance.LoadFile(filePath, (string info) => { //if (string.IsNullOrEmpty(info)) return; try { object obj = JsonUtility.FromJson(info, type); _cache[structName] = obj; if (obj is IBaseData) { IBaseData bd = obj as IBaseData; bd.makeDict(); } totalCount--; if (totalCount == 0) readEnd(); } catch (Exception e) { Console.WriteLine(e); Debug.LogError(filePath); throw; } }); } } catch (Exception ex) { Debug.LogError("fail,error:" + ex.Message); } } public void add<T>(string json) where T : class { Type type = typeof(T); string structName = type.ToString(); object obj = JsonUtility.FromJson(json, type); _cache[structName] = obj; if (obj is IBaseData) { IBaseData bd = obj as IBaseData; bd.makeDict(); } } public void add<T>(T data) where T : class { Type type = typeof(T); string structName = type.ToString(); _cache[structName] = data; if (data is IBaseData) { IBaseData bd = data as IBaseData; bd.makeDict(); } } private void readEnd() { //GameManager.Instance.EventManager.DispatchEvent(new GameEventArgs(WorldEventType.ReadConfigEnd)); //AssetBundleTool.instance.ReadyLoad(); } }
ConfigManager JsonToObject
最新推荐文章于 2025-02-05 20:32:53 发布