/// <summary> /// 加载某个csv /// </summary> public static CsvFile Load(string csvName) { try { // 载入资源 string assetPath = ConfigMgr.ETC_PATH + "/" + csvName + CSV_EXT; byte[] csvBytes = ResourceMgr.Instance.LoadByte(assetPath); // 资源不存在 if (csvBytes == null || csvBytes.Length == 0) { return(null); } // 反序列化 MemoryStream csvStr = new MemoryStream(csvBytes, 0, csvBytes.Length, true, true); CsvFile csv = CsvFileMgr.Deserialize(csvStr); csvStr.Close(); // 返回数据 return(csv); } catch (Exception e) { NIDebug.Log(e.Message); return(null); } finally { // do something } }
/// <summary> /// 等待获取Response结果回调 /// </summary> /// <param name="result">Result.</param> private void WaitGetResponse(IAsyncResult result) { try { webResponse = webRequest.EndGetResponse(result) as HttpWebResponse; if (webResponse != null && webResponse.ContentLength >= 0) { needDownloadBytes = (int)webResponse.ContentLength; } } catch (WebException e) { if (e.Status == WebExceptionStatus.Success) { webResponse = e.Response as HttpWebResponse; } else if (e.Message.IndexOf("(416) Requested Range Not Satisfiable") < 0) { error = -1; } // 打印详细信息 NIDebug.LogException(e); } // 标识已经Get过Response isGetResponse = true; }
/// <summary> /// 移动文件 /// </summary> public static void MoveFile(string sourceFile, string targetFile) { try { FileInfo sourceInfo = new FileInfo(sourceFile); FileInfo targetInfo = new FileInfo(targetFile); if (!sourceInfo.Exists) { Debug.LogWarning(string.Format("不存在源文件 {0}!", sourceFile)); return; } // 如果源文件存在,则需要删除 if (targetInfo.Exists) { targetInfo.Delete(); } // 建立目标目录 CreateDirectory(Path.GetDirectoryName(targetFile)); // 移动所有文件 File.Move(sourceInfo.FullName, targetInfo.FullName); } catch (Exception e) { NIDebug.LogException(e); } }
// 写入文件 public static bool WriteFile(string path, byte[] data) { // 确保目录存在 CreateDirectory(Path.GetDirectoryName(path)); for (int i = 0; i < 10; i++) { try { FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); fs.Write(data, 0, data.Length); fs.Close(); FileInfo fi = new FileInfo(path); if (fi.Exists && (fi.Length > 0 || data.Length == 0)) { return(true); } } catch { } System.Threading.Thread.Sleep(100); } NIDebug.LogError(string.Format("文件写入失败 {0}", path)); return(false); }
// 序列化这行数据 bool Deserialize() { if (mRowData == null) { return(true); } try { // 反序列化 int offset = 0; for (var idx = 0; idx < mOwner.columns.Count; idx++) { LPCValue v; offset += LPCValue.RestoreFromBuffer(mRowData, offset, out v); Add(idx, v); } return(true); } catch (Exception e) { NIDebug.Log(e.Message); return(false); } finally { mRowData = null; } }
/// <summary> /// 创建目录 /// </summary> /// <param name="dir">Dir.</param> public static void CreateDirectory(string dir) { if (Directory.Exists(dir)) { return; } for (int i = 0; i < 10; i++) { try { Directory.CreateDirectory(dir); if (Directory.Exists(dir)) { return; } } catch { } System.Threading.Thread.Sleep(100); } NIDebug.LogError(string.Format("目录创建失败 {0}", dir)); }
/// <summary> /// 打包AB资源 /// </summary> /// <returns><c>true</c>, if A was built, <c>false</c> otherwise.</returns> public static bool SetABName() { Dictionary <string, string> abNameDict = GetFilterDirectories(); if (abNameDict == null) { return(false); } // 清除本地所有的ab ClearAllABName(); // 设置单个资源的ABName foreach (KeyValuePair <string, string> item in abNameDict) { // 黑名单中的不设置 if (blackABDict.ContainsKey(item.Key)) { continue; } if (!SetABName(item.Key, item.Value)) { return(false); } } NIDebug.Log("设置AssetBundle Name完成"); // 刷新编辑器 AssetDatabase.Refresh(); return(true); }
/// <summary> /// 自动给Forms层级排序 /// </summary> private int AutoCalculateDepth(UIBaseForms <MonoBehaviour> forms, int curDepth) { UIPanel parentPanel = forms.GetComponent <UIPanel>(); if (parentPanel == null) { NIDebug.LogWarning("=============自动给Forms层级排序========parentPanel是null======"); return(curDepth); } UIPanel[] childrenPanel = forms.GetComponentsInChildren <UIPanel>(true); //这里的下标0也是parentPanel int parentPanelDepth = parentPanel.depth; int maxDis = 0; for (int i = 0; i < childrenPanel.Length; i++) { int disDepth = childrenPanel[i].depth - parentPanelDepth; childrenPanel[i].depth = curDepth + disDepth; if (disDepth > maxDis) { maxDis = disDepth; } } return(curDepth + maxDis + 1); }
/// <summary> /// 载入AssetBundle资源 /// </summary> public AssetBundle LoadAssetBundle(string bundle) { AssetBundle ab; // 尝试获取已加载过的AssetBundle if (AssetBundleMap.TryGetValue(bundle, out ab) && ab != null) { return(ab); } try { // 载入assetBundle ab = AssetBundle.LoadFromFile(ConfigMgr.ASSETBUNDLES_PATH + "/" + bundle); // 添加到资源管理列表中 AssetBundleMap[bundle] = ab; } catch (Exception e) { // 给出异常提示信息 NIDebug.LogException(e); } // 返回资源 return(ab); }
private static LPCValue Parse(string type, string text) { try { switch (type) { case "auto": return(ParseAutoType(text)); case "string": return(ParseStringType(text)); case "int": return(ParseIntType(text)); case "mapping": return(ParseMappingType(text)); case "array": return(ParseArrayType(text)); default: throw new Exception("bad type to parse"); } } catch (Exception e) { NIDebug.Log("读取csv错误\ntype = {0}, text = {1}", type, text); throw e; } }
/// <summary> /// 载入地资源映射目录 /// </summary> private static IEnumerator LoadResourceDictFile() { // 本地版本文件不存在 string filePath = string.Format("{0}/{1}.bytes", ConfigMgr.ASSETBUNDLES_PATH, RESOURCE_DICT); if (!File.Exists(filePath)) { NIDebug.Log("找不到本地资源映射目录。"); yield break; } // 载入本地版本文件 try { // 读取文件 byte[] verData = File.ReadAllBytes(filePath); // 反序列化 MemoryStream csvStr = new MemoryStream(verData, 0, verData.Length, true, true); mResourceDictCsv = CsvFileMgr.Deserialize(csvStr); csvStr.Close(); verData = null; } catch (Exception e) { NIDebug.LogException(e); } }
/// <summary> /// 删除文件 /// </summary> public static void DeleteFile(string path) { // 文件不存在 if (!File.Exists(path)) { return; } // 尝试删除文件 for (int i = 0; i < 10; i++) { try { File.Delete(path); if (!File.Exists(path)) { return; } } catch { } // 删除失败等待0.1s后重试 System.Threading.Thread.Sleep(100); } NIDebug.LogError(string.Format("文件删除失败 {0}", path)); }
// 协程步进,这里主要是增加了try catch,以及处理从YieldObject继承的我们自己的协程类 static IEnumerator Step(Proxy p) { while (true) { if (p.mIEnumerator == null) { p.Finish(); yield break; } if (!p.IsFinished && p.IsRunning) { try { object yieldObj = p.mIEnumerator.Current; if (yieldObj != null && yieldObj is IYieldObject) { // 我们自己的协程类 if ((yieldObj as IYieldObject).IsDone()) { bool isFin = !p.mIEnumerator.MoveNext(); if (!p.IsFinished) { p.IsFinished = isFin; } } } else { bool isFin = !p.mIEnumerator.MoveNext(); if (!p.IsFinished) { p.IsFinished = isFin; } } } catch (Exception e) { p.IsFinished = true; NIDebug.LogException(e); } } if (p.IsFinished) { p.Finish(); yield break; } else { yield return(p.mIEnumerator.Current); } } }
/// <summary> /// 加载技能文件(仅在验证客户端模式下使用,直接加载resource下的资源) /// </summary> /// <param name="_files">Files.</param> private void LoadSkillActionFile() { if (Platform.IsEditor) { // 载入全部资源 foreach (string filePath in Directory.GetFiles(ConfigMgr.ETC_PATH, "*")) { // meta文件不处理 if (filePath.Contains(".meta")) { continue; } // 转换路径 string tempPath = filePath.Replace("\\", "/"); string ex = Path.GetExtension(tempPath); if (string.Equals(ex, ".xml") && Path.GetFileName(tempPath).Contains("skill_action")) { etcSkillActionList.Add(ResourceMgr.Instance.Load(tempPath).ToString()); } } } else { // 取得skill_action综合文件,加载所有skill_action string resPath = string.Format("Assets/{0}", ConfigMgr.SKILL_ACTION_DICT); string resText = ResourceMgr.Instance.LoadText(resPath); if (string.IsNullOrEmpty(resText)) { NIDebug.Log("加载skill_action_dict文件失败。"); return; } string[] lines = GameUtility.Explode(resText, "\n"); foreach (string line in lines) { if (string.IsNullOrEmpty(line)) { continue; } resText = ResourceMgr.Instance.LoadText(line); if (string.IsNullOrEmpty(resText)) { NIDebug.Log("加载{0}文件失败。", line); continue; } etcSkillActionList.Add(ResourceMgr.Instance.LoadText(line)); } } }
/// <summary> /// Steps the fixed. /// </summary> /// <param name="p">P.</param> static void StepFixed(Proxy p) { // 判断协程是否需要结束 if (p.mIEnumerator == null) { p.Finish(); return; } if (!p.IsFinished && p.IsRunning) { try { object yieldObj = p.mIEnumerator.Current; if (yieldObj != null && yieldObj is IYieldObject) { // 我们自己的协程类 if ((yieldObj as IYieldObject).IsDone()) { bool isFin = !p.mIEnumerator.MoveNext(); if (!p.IsFinished) { p.IsFinished = isFin; } } } else if (yieldObj is UnityEngine.WaitForSeconds || yieldObj is UnityEngine.WaitForEndOfFrame || yieldObj is UnityEngine.WaitForFixedUpdate) { NIDebug.Log("固定协程驱动类型非法, IEnumerator = {0}, Type = {1}", p.mIEnumerator, yieldObj.GetType().ToString()); } else { bool isFin = !p.mIEnumerator.MoveNext(); if (!p.IsFinished) { p.IsFinished = isFin; } } } catch (Exception e) { p.IsFinished = true; NIDebug.LogException(e); } } // 判断是否需要结束 if (p.IsFinished) { p.Finish(); } }
/// <summary> /// 获取数据值 /// </summary> /// <returns>The value.</returns> /// <typeparam name="T">The 1st type parameter.</typeparam> public T GetValue <T>() { if (mValue != null && mValue.GetValueType() == typeof(T)) { return((mValue as MixedValueImpl <T>).Value); } NIDebug.LogError("MixedValue不是{0}", typeof(T).Name); return(default(T)); }
/// <summary> /// 清除所有的AssetBundleName /// </summary> public static void ClearAllABName() { string[] allNames = AssetDatabase.GetAllAssetBundleNames(); for (int j = 0; j < allNames.Length; j++) { AssetDatabase.RemoveAssetBundleName(allNames[j], true); } NIDebug.Log("清除完成"); }
private static LPCValue ParseIntType(string text) { int i; if (!int.TryParse(text, out i)) { NIDebug.LogError("无法将 " + text + " 转换为int"); i = 0; } return(LPCValue.Create(i)); }
public static void Call(SafeCallFunc f) { try { f(); } catch (System.Exception e) { NIDebug.LogException(e); } }
/// <summary> /// Gens the patch files. /// </summary> /// <returns>The patch files.</returns> /// <param name="patchPatch">Patch patch.</param> /// <param name="versionItemSize">Version item size.</param> /// <param name="abPatchDic">Ab patch dic.</param> private static Dictionary <string, string> GenPatchFiles(string patchPath, string abPath, Dictionary <string, List <object> > versionItemInfo, ref Dictionary <string, string> abPatchDic) { Dictionary <string, string> patchVersionDic = new Dictionary <string, string>(); List <string> filterAB = new List <string>(); foreach (KeyValuePair <string, List <string> > item in AssetBundleNameTools.patchAbDict) { filterAB.Clear(); string md5Str = string.Empty; foreach (string reg in item.Value) { List <string> bundles = versionItemInfo.Keys.Where(bundle => (Regex.IsMatch(bundle, reg))).ToList <string>(); if (bundles.Count == 0) { NIDebug.LogError("生成patch时 {0} 筛选出来的文件个数为0,请检查!", reg); continue; } // 对文件按文件名称进行排序 bundles.Sort(delegate(string b1, string b2) { return(b1.CompareTo(b2)); }); foreach (string bundle in bundles) { filterAB.Add(string.Format("{0}{1}", abPath, bundle)); md5Str += versionItemInfo[bundle][0]; if (abPatchDic.ContainsKey(bundle)) { NIDebug.LogError(string.Format("{0}重复放在了{1}和{2}中,请检查!", bundle, abPatchDic[bundle], item.Key)); continue; } abPatchDic.Add(bundle, item.Key); } } string md5 = NIEditorUtility.GetStrMD5(md5Str); NIEditorUtility.Zip(filterAB.ToArray(), string.Format("{0}{1}_{2}.zip", patchPath, item.Key, md5)); patchVersionDic.Add(item.Key, md5); } return(patchVersionDic); }
private void PushForms(string formsName) { if (!mFormsStackName.ContainsKey(formsName)) { mFormsStackName.Add(formsName, mCurStackFormsIndex); mFormsStackIndex.Add(mCurStackFormsIndex, formsName); } else { NIDebug.LogWarning("**************功能窗口栈已有此窗口*****************"); } }
private static LPCValue ParseAutoType(string text) { if (text.Length < 1) { return(LPCValue.Create(text)); } char first_char = text [0]; if (first_char == '@') { // alias string alias = text.Substring(1); if (!AliasMgr.ContainsAlias(alias)) { NIDebug.LogError("字段没有配置别名 " + alias); return(LPCValue.Create(text)); } object v = AliasMgr.Get(alias); if (v is string) { return(LPCValue.Create((string)v)); } if (v is int) { return(LPCValue.Create((int)v)); } throw new Exception(string.Format("Unexpected alias name: {0}", alias)); } if ((first_char == '"') || (first_char == ':')) { // string or buffer return(LPCRestoreString.RestoreFromString(text)); } if ((first_char == '(') && (text.Length > 1)) { char second_char = text [1]; if ((second_char == '{') || (second_char == '[')) { // mapping or array return(LPCRestoreString.RestoreFromString(text)); } } if (((first_char >= '0') && (first_char <= '9')) || (first_char == '.') || (first_char == '-')) { // number return(LPCRestoreString.RestoreFromString(text)); } return(LPCValue.Create(text)); }
/// <summary> /// Dispatchs the service. /// </summary> /// <returns>The service.</returns> /// <param name="i">The index.</param> /// <param name="owner">Owner.</param> /// <param name="name">Name.</param> /// <param name="fixedMode">If set to <c>true</c> fixed coro.</param> public static Proxy DispatchService(IEnumerator i, UnityEngine.Object owner, string name, bool fixedMode) { // mInstance对象不存在 if (mInstance == null) { return(null); } // 没有owner对象 if (owner == null) { NIDebug.LogWarning("owner 是空的,i = {0}, name = {1}", i, name); return(null); } Dictionary <string, Proxy> cm = (!fixedMode ? mCoroutionMap : mCoroutionFixedMap); List <Proxy> cl = (!fixedMode ? mCoroutionList : mCoroutionFixedList); #if UNITY_EDITOR if (cm.Count > 500) { NIDebug.LogWarning("Coroutine数量太多!"); } #endif // 没有名字,自动取一个 if (string.IsNullOrEmpty(name)) { name = GameUtility.GetUniqueName("AnonymousCoroutine"); } // 如果已经包含了该协程名的协程 if (cm.ContainsKey(name)) { NIDebug.LogWarning(string.Format("重名Coroutine {0}, 失败!", name)); return(null); } Proxy p = new Proxy(name, i, owner, fixedMode); cm.Add(name, p); cl.Add(p); if (!fixedMode) { mInstance.StartCoroutine(Step(p)); } else { StepFixed(p); } return(p); }
/// <summary> /// 创建窗口 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="formsName"></param> /// <returns></returns> private T _CreateForms <T>(string formsName, Transform parentForms = null, bool isDontUnload = false) where T : UIBaseFormsRoot { GameObject prefabGo = ResourceMgr.Instance.Load(string.Format(PREFAB_PATH, formsName), isDontUnload) as GameObject; if (prefabGo == null) { NIDebug.LogError("**********************路径下没有这个窗体预制体***************************" + formsName); return(null); } GameObject go = GameObject.Instantiate(prefabGo) as GameObject; if (go == null) { return(null); } T formsScript = go.GetComponent <T>(); if (formsScript == null) { formsScript = go.AddComponent <T>(); } if (formsScript == null) { NIDebug.LogError("**********************不存在此脚本***************************"); return(null); } go.name = formsName; Transform t = go.transform; if (parentForms != null) { t.parent = parentForms; } else { if (mFormsUIRoot != null) { t.parent = mFormsUIRoot.transform; } } t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; t.localScale = Vector3.one; mFormsDic[formsName] = formsScript; return(formsScript); }
// 根据列名获取数据 public T Query <T>(string columnName, T def = default(T)) { // 不是获取主key值,且还没有序列化完成,立刻序列化 if (columnName != mOwner.primaryKey && mRowData != null && !Deserialize()) { NIDebug.Log("csv序列化失败({0})", mOwner.Name); return(def); } int index; if (mOwner.columns.TryGetValue(columnName, out index)) { LPCValue prop = mProperties[index]; // 如果是LPCValue类型 if (typeof(T) == typeof(LPCValue)) { return((T)(object)prop); } // 不是string数据,直接转换 if (!prop.IsString) { return(prop.As <T>()); } // 就是要string,直接返回 if (typeof(T) == typeof(string)) { return(prop.As <T>()); } // 如果外部不是想要string,但是却得到了一个空string // 则表示csv表格上填写的是空值,此时返回默认值 if (prop.AsString == string.Empty) { return(def); } // 外部不是想要string,却得到了有字符的string // 走到这儿的时候已经出错了,直接使用As借口中的异常处理即可 return(prop.As <T>()); } else { NIDebug.Log("{0}.csv 没有列 {1}。", mOwner.Name, columnName); } // 返回默认值 return(def); }
private void UnregisterEvent(string eventType, Delegate del) { Delegate temp; if (_eventDic.TryGetValue(eventType, out temp)) { Delegate.Remove(temp, del); } else { NIDebug.Log("===============不存在这个委托,无需移除=================="); } }
// Use this for initialization IEnumerator Start() { try { Init(); } catch (Exception e) { NIDebug.LogException(e); } yield break; }
private void PopForms(string formsName) { if (!mFormsStackIndex[mCurStackFormsIndex].Equals(formsName)) { NIDebug.LogWarning("*************此窗口不是栈顶窗口,无法Pop****************"); return; } if (mFormsStackName.ContainsKey(formsName)) { mFormsStackIndex.Remove(mFormsStackName[formsName]); mFormsStackName.Remove(formsName); } }
/// <summary> /// 获取属性字段描述 /// </summary> public static string GetFieldDesc(string field, string attrib) { CsvRow data = FieldsCsv.FindByKey(field); // 没有配置的字段 if (data == null) { NIDebug.Log("fields.csv未配置字段{0}", field); return(string.Empty); } // 返回数据 return(data.Query <string>(attrib)); }
/// <summary> /// 获取字段对应的道具 /// </summary> public static int GetFieldItemClassId(string field) { CsvRow data = FieldsCsv.FindByKey(field); // 没有配置的字段 if (data == null) { NIDebug.Log("fields.csv未配置字段{0}", field); return(-1); } // 返回数据 return(data.Query <int>("item_class_id")); }