using UnityEngine; using System; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Text.RegularExpressions; using LuaInterface; using GameLogic; using UnityEngine.UI; using DG.Tweening; using ResUpdate; using GameCore; using System.Reflection; using Spine.Unity; #if UNITY_EDITOR using UnityEditor; #endif namespace GameLogic { public static class Util { public static string packGameVersion = ""; public static string updateGameVersion = ""; public static string netGameVersion = ""; public static Color gray = Color.gray; private static List luaPaths = new List(); public static string GetDownloadPackageUrl() { string download_url = string.Empty; #if UNITY_IOS download_url = AppConst.Download_ipa_Url; #else download_url = AppConst.Download_apk_Url; #endif return download_url; } public static bool IsFileExist(string fileName) { return File.Exists(Util.DataPath + fileName); } public static bool IsExracted() { bool isExists = Directory.Exists(DataPath) && Directory.Exists(DataPath + "lua/") && File.Exists(DataPath + AppConst.LoadingMD5Flie); return isExists; } public static bool NeedExtractResource() { return false; if (!IsExracted()) return true; return CompareGameVersion(packGameVersion, updateGameVersion) > 0; } public static int CompareGameVersion(string version1, string version2) { float result = 0; if (string.IsNullOrEmpty(version1) || string.IsNullOrEmpty(version2)) { return version1.CompareTo(version2); } else { var temp1 = version1.Split('.'); var temp2 = version2.Split('.'); float first1 = 0; float.TryParse(temp1[0], out first1); float first2 = 0; float.TryParse(temp2[0], out first2); float middle1 = 0; float.TryParse(temp1[1], out middle1); float middle2 = 0; float.TryParse(temp2[1], out middle2); float last1 = 0; float.TryParse(temp1[2], out last1); float last2 = 0; float.TryParse(temp2[2], out last2); if (first1 != first2) result = first1 - first2; else if (middle1 != middle2) result = middle1 - middle2; else result = last1 - last2; } if (result > 0) return 1; else if (result == 0) return 0; else return -1; } public static int Int(object o) { return Convert.ToInt32(o); } public static float Float(object o) { return (float)Math.Round(Convert.ToSingle(o), 2); } public static long Long(object o) { return Convert.ToInt64(o); } public static int Random(int min, int max) { return UnityEngine.Random.Range(min, max); } public static float Random(float min, float max) { return UnityEngine.Random.Range(min, max); } public static string Uid(string uid) { int position = uid.LastIndexOf('_'); return uid.Remove(0, position + 1); } public static long GetTime() { TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks); return (long)ts.TotalMilliseconds; } public static string GetDateTime() { return DateTime.Now.ToString(); } public static string GetPlatformVersion() { App.GameMgr.StartCoroutine(GetPlatformText("Platform/" + AppConst.GameVersionFile)); return packGameVersion; } private static IEnumerator GetPlatformText(string filePath) { string versionFilePath = DataPath + filePath; if (File.Exists(versionFilePath)) { var lines = File.ReadAllLines(versionFilePath); if (lines.Length > 0) { if (!string.IsNullOrEmpty(lines[0])) { packGameVersion = lines[0].Trim(); } } yield return null; } else { yield return App.GameMgr.StartCoroutine(GetPackageText(filePath)); } } private static IEnumerator GetPackageText(string fileName) { string filePath = GetOriginalPath() + fileName; WWW www = new WWW(filePath); yield return www; if (!string.IsNullOrEmpty(www.error)) { XDebug.Log.error("File " + fileName + " no exist in " + filePath + ",Please check it."); } else { if (www.isDone) { packGameVersion = www.text.Trim(); } } } /// /// 搜索子物体组件-GameObject版 /// public static T Get(GameObject go, string subnode) where T : Component { if (go != null) { Transform sub = go.transform.Find(subnode); if (sub != null) return sub.GetComponent(); } return null; } /// /// 搜索子物体组件-Transform版 /// public static T Get(Transform go, string subnode) where T : Component { if (go != null) { Transform sub = go.Find(subnode); if (sub != null) return sub.GetComponent(); } return null; } /// /// 搜索子物体组件-Component版 /// public static T Get(Component go, string subnode) where T : Component { return go.transform.Find(subnode).GetComponent(); } /// /// 添加组件 /// public static T Add(GameObject go) where T : Component { if (go != null) { T[] ts = go.GetComponents(); for (int i = 0; i < ts.Length; i++) { if (ts[i] != null) GameObject.Destroy(ts[i]); } return go.gameObject.AddComponent(); } return null; } /// /// 添加组件 /// public static T Add(Transform go) where T : Component { return Add(go.gameObject); } public static EventTriggerListener GetEventTriggerListener(GameObject go) { EventTriggerListener triggerListener = null; if (go != null) { triggerListener = go.GetComponent(); if (triggerListener == null) { triggerListener = go.AddComponent(); } } return triggerListener; } public static EventTriggerListener GetEventTriggerListenerWithNil(GameObject go) { EventTriggerListener triggerListener = null; if (go != null) { triggerListener = go.GetComponent(); } return triggerListener; } /// /// 查找子对象 /// public static GameObject Child(GameObject go, string subnode) { return Child(go.transform, subnode); } /// /// 查找子对象 /// public static GameObject Child(Transform go, string subnode) { Transform tran = go.Find(subnode); if (tran == null) return null; return tran.gameObject; } public static GameObject GetGameObject(GameObject root, string objName) { if (root == null) return null; return GetGameObject(root.transform, objName); } public static GameObject GetGameObject(Transform root, string objName) { if (root == null || string.IsNullOrEmpty(objName)) return null; if (root.name.CompareTo(objName) == 0) return root.gameObject; var trans = FindChild(root, objName); return trans == null ? null : trans.gameObject; } public static Transform GetTransform(Transform root, string objName) { if (root == null) return null; if (root.name.CompareTo(objName) == 0) return root.transform; var trans = FindChild(root, objName); return trans == null ? null : trans; } public static Transform GetTransform(GameObject root, string objName) { if (root == null) return null; return GetTransform(root.transform, objName); } public static Transform FindChild(Transform root, string objName) { var obj = root.Find(objName); if (obj != null) return obj; for (int i = 0; i < root.childCount; i++) { obj = FindChild(root.GetChild(i), objName); if (obj != null) return obj; } return null; } /// /// 取平级对象 /// public static GameObject Peer(GameObject go, string subnode) { return Peer(go.transform, subnode); } /// /// 取平级对象 /// public static GameObject Peer(Transform go, string subnode) { Transform tran = go.parent.Find(subnode); if (tran == null) return null; return tran.gameObject; } /// /// 计算字符串的MD5值 /// /// public static string md5(string source) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.UTF8.GetBytes(source); byte[] md5Data = md5.ComputeHash(data, 0, data.Length); md5.Clear(); string destString = ""; for (int i = 0; i < md5Data.Length; i++) { destString += System.Convert.ToString(md5Data[i], 16).PadLeft(2, '0'); } destString = destString.PadLeft(32, '0'); return destString; } /// /// 计算文件的MD5值 /// public static string md5file(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } } /// /// 计算buffer的MD5值 /// public static string md5bytes(byte[] buffer) { try { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(buffer); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5bytes() fail, error:" + ex.Message); } } /// /// 清除所有子节点 /// public static void ClearChild(Transform go) { if (go == null) return; for (int i = go.childCount - 1; i >= 0; i--) { GameObject.DestroyImmediate(go.GetChild(i).gameObject); } } /// /// 清理内存 /// public static void ClearMemory() { App.LuaMgr.LuaGC(); Resources.UnloadUnusedAssets(); GC.Collect(); } /// /// 取得数据存放目录 /// public static string DataPath { get { string game = AppConst.AppName.ToLower(); if (Application.isMobilePlatform) { return Application.persistentDataPath + "/" + game + "/" + AppConst.PlatformPath + "/"; } if (AppConst.DebugMode) { return Application.dataPath + "/" + AppConst.AssetDir + "/"; } if (Application.platform == RuntimePlatform.OSXEditor) { int i = Application.dataPath.LastIndexOf('/'); return Application.dataPath.Substring(0, i + 1) + game + "/" + AppConst.PlatformPath + "/"; } return "c:/" + game + "/" + AppConst.PlatformPath + "/"; } } public static string GetRelativePath() { if (Application.isEditor) // // return "file:///" + DataPath; //+ System.Environment.CurrentDirectory.Replace("\\", "/") + "/Assets/" + AppConst.AssetRoot + "/"; else if (Application.isMobilePlatform || Application.isConsolePlatform) return "file:///" + DataPath; else // For standalone player. return "file://" + Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; } public static string GetOriginalPath() { if (Application.isEditor) return "file:///" + Application.dataPath + "/" + AppConst.AssetRoot + "/"; else if (Application.isMobilePlatform || Application.isConsolePlatform) { if (Application.platform == RuntimePlatform.Android) return "jar:file://" + Application.dataPath + "!/assets/" + AppConst.PlatformPath + "/"; else if (Application.platform == RuntimePlatform.IPhonePlayer) return "file:///" + Application.dataPath + "/Raw/" + AppConst.PlatformPath + "/"; else return "file:///" + Application.dataPath + "/" + AppConst.AssetRoot + "/"; } else // For standalone player. return "file://" + Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; } public static void WriteFileToDataPath(string name, string content) { string outfile = DataPath + name; string dir = Path.GetDirectoryName(outfile); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (File.Exists(outfile)) { File.Delete(outfile); } File.WriteAllText(outfile, content); } public static string ReadFileFromDataPath(string name) { string content = null; string outfile = DataPath + name; if (File.Exists(outfile)) { content = File.ReadAllText(outfile); } return content; } public static string GetAvaliableRelativePath() { var needExract = NeedExtractResource(); if (needExract) return GetOriginalPath(); else return GetRelativePath(); } public static string GetAvaliableRelativePath_File() { var needExract = NeedExtractResource(); if (needExract) return GetOriginalPath_File(); else return GetRelativePath_File(); } public static string GetOriginalPath_File() { if (Application.isEditor) return Application.dataPath + "/" + AppConst.AssetRoot + "/"; else if (Application.isMobilePlatform || Application.isConsolePlatform) { if (Application.platform == RuntimePlatform.Android) return "jar:file://" + Application.dataPath + "!/assets/" + AppConst.PlatformPath + "/"; else if (Application.platform == RuntimePlatform.IPhonePlayer) return Application.dataPath + "/Raw/" + AppConst.PlatformPath + "/"; else return "file:///" + Application.dataPath + "/" + AppConst.AssetRoot + "/"; } else // For standalone player. return "file://" + Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; } public static string GetRelativePath_File() { if (Application.isEditor) // // return DataPath; //+ System.Environment.CurrentDirectory.Replace("\\", "/") + "/Assets/" + AppConst.AssetRoot + "/"; else if (Application.isMobilePlatform || Application.isConsolePlatform) return DataPath; else // For standalone player. return Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; } /// /// 应用程序内容路径 /// public static string AppContentPath() { string path = string.Empty; switch (Application.platform) { case RuntimePlatform.Android: path = Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; break; case RuntimePlatform.IPhonePlayer: path = Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; break; default: path = Application.streamingAssetsPath + "/" + AppConst.PlatformPath + "/"; break; } return path; } public static string AppRootPath() { string path = string.Empty; switch (Application.platform) { case RuntimePlatform.Android: path = "jar:file://" + Application.dataPath + "!/assets/" + AppConst.PlatformPath + "/"; break; case RuntimePlatform.IPhonePlayer: path = Application.dataPath + "/Raw/" + AppConst.PlatformPath + "/"; break; default: path = Application.dataPath + "/" + AppConst.AssetRoot + "/"; break; } return path; } /// /// 取得行文本 /// public static string GetFileText(string path) { return File.ReadAllText(path); } /// /// 网络可用 /// public static bool NetAvailable { get { return Application.internetReachability != NetworkReachability.NotReachable; } } /// /// 是否是无线 /// public static bool IsWifi { get { return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork; } } public static void SetLogLevel(int level) { GameCore.BaseLogger.level = (LogLevel)level; } public static void Log(params object[] pars) { XDebug.Log.l(pars); } public static void LogWarning(string str) { XDebug.Log.warning(str); } public static void LogError(string str) { XDebug.Log.error(str); } /// /// 防止初学者不按步骤来操作 /// /// public static int CheckRuntimeFile() { if (!Application.isEditor) return 0; string streamDir = Application.dataPath + "/" + AppConst.AssetRoot + "/"; if (!Directory.Exists(streamDir)) { return -1; } else { string[] files = Directory.GetFiles(streamDir); if (files.Length == 0) return -1; if (!File.Exists(streamDir + AppConst.LoadingMD5Flie)) { return -1; } } string sourceDir = AppConst.FrameworkRoot + "/ToLua/Source/Generate/"; if (!Directory.Exists(sourceDir)) { return -2; } else { string[] files = Directory.GetFiles(sourceDir); if (files.Length == 0) return -2; } return 0; } /// /// 执行Lua方法 /// public static void CallMethod(string module, string func, params object[] args) { App.LuaMgr.CallFunction(module + "." + func, args); } /// /// 检查运行环境 /// public static bool CheckEnvironment() { #if UNITY_EDITOR int resultId = Util.CheckRuntimeFile(); if (resultId == -1) { Debug.LogError("没有找到框架所需要的资源,单击Game菜单下Build xxx Resource生成!!"); EditorApplication.isPlaying = false; return false; } else if (resultId == -2) { Debug.LogError("没有找到Wrap脚本缓存,单击Lua菜单下Gen Lua Wrap Files生成脚本!!"); EditorApplication.isPlaying = false; return false; } if (Application.loadedLevelName == "Test" && !AppConst.DebugMode) { Debug.LogError("测试场景,必须打开调试模式,AppConst.DebugMode = true!!"); EditorApplication.isPlaying = false; return false; } #endif return true; } /// /// 添加点击事件 /// public static void AddClick(GameObject go, LuaFunction luafunc) { if (go == null || luafunc == null) return; go.GetComponent