using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; using System.Text.RegularExpressions; #if !COMBAT_SERVER using UnityEngine; #endif using System.IO; using System.Runtime.Serialization.Formatters.Binary; #if !COMBAT_SERVER using UnityEngine.Profiling; #endif using System.Security.Cryptography; using Fort23.UTool; namespace Utility { public static class UtilTools { #if !COMBAT_SERVER public static List allDontDestroyOnLoad = new List(); #endif private static int m_seed = 0; private static StringBuilder sb; public static long oneDay = 86400000; public static int GenerateSeed() { m_seed++; return m_seed; } public static float FrameToDuration(int frame) { return frame * 0.02f; } public static string GetGUID() { System.Guid guid = new Guid(); guid = Guid.NewGuid(); string str = guid.ToString(); return str; } #if !COMBAT_SERVER public static void SetDontDestroyOnLoad(GameObject go) { if (allDontDestroyOnLoad.Contains(go)) { return; } GameObject.DontDestroyOnLoad(go); allDontDestroyOnLoad.Add(go); } public static int DurationToFrame(float duration) { return (int)(duration / Time.fixedDeltaTime); } #endif // public static int RoundToInt(float value) // { // return (int)System.Math.Round(value); // } #if !COMBAT_SERVER public static string CombineString(params string[] strs) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < strs.Length; i++) { sb.Append(strs[i]); } return sb.ToString(); } public static string CombineString(params object[] strs) { if (sb == null) { sb = new StringBuilder(); } sb.Clear(); //StringBuilder sb = new StringBuilder(); for (int i = 0; i < strs.Length; i++) { sb.Append(strs[i]); } return sb.ToString(); } // /// // /// 获取描述文本 // /// // /// // /// // /// // public static string GetDscString(string a, float[] b) // { // if (a == "") // return ""; // for (int i = 0; i < b?.Length; i++) // { // string d = b[i].ToString(); // string c = "{" + i + "}"; // a = a.Replace(c, d); // } // // return a; // } /// /// 获取描述文本 /// /// /// /// public static string GetDscString(string a, float[] b) { if (a == "") return ""; for (int i = 0; i < b?.Length; i++) { string d = b[i].ToString("0.##"); string c = "{" + i + "}"; a = a.Replace(c, d); } return a; } /// /// 获取描述文本 /// /// /// /// public static string GetDscString(string a, string[] b) { if (a == "") return ""; for (int i = 0; i < b?.Length; i++) { string d = b[i].ToString(); string c = "{" + i + "}"; a = a.Replace(c, d); } return a; } public static string GetSignaturesInfo() { #if UNITY_ANDROID&&!UNITY_EDITOR AndroidJavaClass contextClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject context = contextClass.GetStatic("currentActivity"); AndroidJavaObject packageManager = context.Call("getPackageManager"); string packageName = context.Call("getPackageName"); int flags = packageManager.GetStatic("GET_SIGNATURES"); AndroidJavaObject packageInfo = packageManager.Call("getPackageInfo", packageName, flags); AndroidJavaObject[] signatures = packageInfo.Get("signatures"); // Get the first signature (assuming only one signature) AndroidJavaObject signature = signatures[0]; // Convert signature to bytes byte[] signatureBytes = signature.Call("toByteArray"); // Compute SHA256 hash SHA256 sha256 = SHA256.Create(); byte[] hashBytes = sha256.ComputeHash(signatureBytes); // Convert bytes to hex string StringBuilder builder = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { // Debug.Log(hashBytes[i].ToString("x2").ToUpperInvariant()); builder.Append(hashBytes[i].ToString("X2")); if (i < hashBytes.Length - 1) { builder.Append(":"); } } string sha256Signature = builder.ToString(); return sha256Signature; #else return ""; #endif } /// /// 正则匹配 /// /// /// "mydata|mydata|" public static bool MatchingMouna(ref string str, string data) { MatchCollection m = Regex.Matches(str, "(" + data + ")", RegexOptions.Multiline); for (int i = 0; i < m.Count; i++) { string m1 = Regex.Replace(m[i].ToString(), "\\$", "\\$"); m1 = Regex.Replace(m1, "\\^", "\\^"); string xingxing = ""; for (int j = 0; j < m1.Length; j++) xingxing += "*"; str = Regex.Replace(str, m1, xingxing); } if (m.Count > 0) { return true; } else { return false; } //LogManager.Instance.Log(str + " " + data); } /// /// 设置对象的层 /// /// /// /// public static void SetGameObjctLayer(string layerName, GameObject obj, bool isChild = true) { int layerIdx = LayerMask.NameToLayer(layerName); if (isChild) SetChildLayer(layerIdx, obj.transform); else { obj.layer = layerIdx; } } /// /// 设置对象的层 /// /// /// /// public static void SetGameObjctLayer(int layer, GameObject obj, bool isChild = true) { //int layerIdx = LayerMask.NameToLayer(layerName); if (isChild) SetChildLayer(layer, obj.transform); else { obj.layer = layer; } } private static void SetChildLayer(int layerIdx, Transform obj) { obj.gameObject.layer = layerIdx; for (int i = 0; i < obj.childCount; i++) { SetChildLayer(layerIdx, obj.GetChild(i)); } } public static IPEndPoint CombineIPAddress(string host, int port) { return new IPEndPoint(IPAddress.Parse(host), port); } public static bool IsStringLetterAndNumber(string content) { if (content.Length == 0) { return false; } int asciiCount = Regex.Matches(content, "[a-zA-Z0-9]").Count; return (content.Length > asciiCount) ? false : true; } public static bool IsArrayValid(object array) { if (array == null || !(array is Array) || (array as Array).Length == 0) { return false; } return true; } public static Texture2D GetTexture(string path) { if (string.IsNullOrEmpty(path)) return null; if (!File.Exists(path)) return null; byte[] data = File.ReadAllBytes(path); Texture2D textrue = new Texture2D(512, 512); textrue.LoadImage(data); return textrue; } private static string m_bannedWorlds; public static bool IsBannedWord(string rolename) { return false; } #if UNITY_EDITOR /// /// 获取场景中全部对象 /// /// /// public static List GetAllSceneObj() { List ts = new List(); //HierarchyProperty. //EditorSceneManager. GameObject[] go = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects(); //LogTool.Log(go.Length); AddObjcet(ts, go); go = Utility.UtilTools.allDontDestroyOnLoad.ToArray(); AddObjcet(ts, go); return ts; } //public static string GetModelName(GlobalConfig.LevelType _type, MapUnit unit) //{ // string str =FixationString.empty; // switch (unit) // { // case MapUnit.Wall: // str = _type.SplitToString() + "_Wall_"; // break; // case MapUnit.Coin: // return _type.SplitToString() + "_Seed"; // case MapUnit.Gate: // return _type.SplitToString() + "_Gate"; // case MapUnit.Player: // return "Player"; // case MapUnit.WallVisible: // return _type.SplitToString() + "_WallInvisible"; // case MapUnit.CoinVisible: // return _type.SplitToString() + "SeedInvisible"; // case MapUnit.BlockLight: // case MapUnit.BlockBalance: // case MapUnit.BlockNormal: // case MapUnit.BlockSleep: // case MapUnit.BlockGravity: // return "Block" + _type.SplitToString(); // case MapUnit.Wall_DestroyAble: // return "Wall_DestroyAble"; // } // return str; //} /// private static void AddObjcet(List ts, GameObject[] go) { for (int i = 0; i < go.Length; i++) { if (!go[i]) continue; //if (!go[i].gameObject) // continue; T[] objs = go[i].transform.GetComponentsInChildren(true); for (int j = 0; j < objs.Length; j++) { ts.Add(objs[j]); } } } #endif public static string GetMD5(string inStr) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] InBytes = Encoding.UTF8.GetBytes(inStr); byte[] OutBytes = md5.ComputeHash(InBytes); string OutString = ""; for (int i = 0; i < OutBytes.Length; i++) { OutString += OutBytes[i].ToString("x2"); } //LogTool.Log(OutString); if (OutString.Length > 8) OutString = OutString.Substring(0, 8); return OutString; } // DES加密 public static string DESEncrypt(string pToEncrypt, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt); // if (sKey.Length > 8) sKey = sKey.Substring(0, 8); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); //LogTool.Log(inputByteArray.Length + " 加密后" + ret.SplitToString().Length); return ret.ToString(); } // DES解密 public static string DESDecrypt(string pToDecrypt, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } public static string BASE64_Decode(string data) { byte[] bytes = Convert.FromBase64String(data); return Encoding.UTF8.GetString(bytes); } public static string GetMD5HashFromFile(byte[] data) { try { // FileStream file = new FileStream(filename,FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(data); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (System.Exception ex) { LogTool.Log("错误信息:" + ex); return null; } } public static string FormatTwoTime(int totalSeconds) { int minutes = totalSeconds / 60; string mm = minutes < 10f ? "0" + minutes : minutes.ToString(); int seconds = (totalSeconds - (minutes * 60)); string ss = seconds < 10 ? "0" + seconds : seconds.ToString(); return string.Format("{0}:{1}", mm, ss); } // public static string ToStringEx(this long i) // { // // if (isShowLongEx) // { // if (i >= 10000000000) // return (i / 1000000000) + "B"; // else if (i >= 10000000) // return (i / 1000000) + "M"; // else if (i >= 10000) // return (i / 1000) + "K"; // } // // return i.ToString(); // } /// /// 获取目标小数位的str /// /// /// public static string GetTargetDecimalPlaceStr(int n) { string str = ""; if (n >= 100) //整数大于两位数保留一位小数 { int n1 = (int)(n * 10); n = n1 / 10; str = n.ToString(CultureInfo.InvariantCulture); } else { //保留两位小数 int n1 = (int)(n * 100); n = n1 / 100; str = n.ToString(CultureInfo.InvariantCulture); } return str; } public static long Round(this float number) { return (long)Math.Ceiling(number); } /// /// 四舍五入到整数 /// /// /// public static int RoundToInt(this float value) { // float tempValue = value.Round(0); // int finalValue = Mathf.FloorToInt(tempValue); Math.Ceiling(value); return (int)Math.Ceiling(value); ; } public static string ToStringEx(this long number) { // if (number > 1000000000000) // { // float n = number / 1000000000000f; // string str = ""; // str = GetTargetDecimalPlaceStr((int)n); // return str + "t"; // } // // if (number > 1000000000) // { // float n = number / 1000000000f; // string str = ""; // str = GetTargetDecimalPlaceStr((int)n); // return str + "b"; // } if (number > 1000000) { float n = number / 10000f; string str = ""; str = GetTargetDecimalPlaceStr((int)n); return str + "m"; } if (number > 100000) { float n = number / 1000f; string str = ""; str = GetTargetDecimalPlaceStr((int)n); return str + "k"; } return number.ToString(); } public static string ToStringEx(this int number) { // if (number > 1000000000000) // { // float n = number / 1000000000000f; // string str = ""; // str = GetTargetDecimalPlaceStr((int)n); // return str + "t"; // } // // if (number > 1000000000) // { // float n = number / 1000000000f; // string str = ""; // str = GetTargetDecimalPlaceStr((int)n); // return str + "b"; // } if (number > 1000000) { float n = number / 10000f; string str = ""; str = GetTargetDecimalPlaceStr((int)n); return str + "m"; } if (number > 100000) { float n = number / 1000f; string str = ""; str = GetTargetDecimalPlaceStr((int)n); return str + "k"; } return number.ToString(); // // if (isShowLongEx) // { // if (i >= 10000000000) // return (i / 1000000000) + "B"; // else if (i >= 10000000) // return (i / 1000000) + "M"; // else if (i >= 10000) // return (i / 1000) + "K"; // } // // return i.ToString(); } #endif /// /// 时间(秒)转换位小时分钟秒 /// /// /// public static string TimeToHSM(long miao) { long fen = miao / 60; miao = miao % 60; long xiaoShi = fen / 60; long tian = xiaoShi / 24; xiaoShi = xiaoShi % 24; fen = fen % 60; if (tian > 0) { return $"{tian}天{xiaoShi}小时"; } else { if (xiaoShi <= 0 && fen <= 59) { return $"{fen}分{miao}秒"; } else { return $"{xiaoShi}小时{fen}分"; } } } /// /// 时间(秒)转换位小时分钟秒 /// /// /// public static string TimeToHSM1(long miao) { long fen = miao / 60; miao = miao % 60; long xiaoShi = fen / 60; long tian = xiaoShi / 24; xiaoShi = xiaoShi % 24; fen = fen % 60; if (tian <= 0 && xiaoShi <= 0) { return $"{fen}分钟"; } else if (tian <= 0 && xiaoShi > 0) { return $"{xiaoShi}小时"; } else if (tian >= 1) { return $"{tian}天"; } return ""; } public static string GeiLxTime(long miao) { long fen = miao / 60; miao = miao % 60; long xiaoShi = fen / 60; long tian = xiaoShi / 24; xiaoShi = xiaoShi % 24; fen = fen % 60; if (tian <= 0 && xiaoShi <= 0) { return $"离线{fen}分钟"; } else if (tian <= 0 && xiaoShi > 0) { return $"离线{xiaoShi}小时"; } else if (tian >= 1 && tian <= 7) { return $"离线{tian}天"; } else if (tian > 7) { return "离线七天以上"; } return ""; } /// /// 类型1 :小于1天后显示分和秒 /// /// /// /// public static string TimeToHSM(long miao, int type1) { long fen = miao / 60; miao = miao % 60; long xiaoShi = fen / 60; long tian = xiaoShi / 24; xiaoShi = xiaoShi % 24; fen = fen % 60; if (tian > 0) { return $"{tian}天{xiaoShi}小时"; } else { string key = ""; switch (type1) { case 1: return $"{fen}分{miao}秒"; break; default: break; } return key; } } /// 获取秒级别时间戳(10位) public static long GetTimestampToSeconds() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds); } /// 获取毫秒级别时间戳(13位) public static long GetTimeStampToMilliseconds() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds); } public static long GetTimestampToSeconds(int value) { DateTime dateTime = new DateTime(value, DateTimeKind.Utc); TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds); } /// /// 时间戳转时间结构 秒 /// /// /// public static DateTime ConvertUnixTimestamp(double unixTimestamp) { DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime convertedTime = unixStartTime.AddSeconds(unixTimestamp).ToLocalTime(); return convertedTime; } /// ///时间戳转时间结构 毫秒 /// /// /// public static DateTime ConvertUnixTimestampForMillis(double unixTimestamp) { DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime convertedTime = unixStartTime.AddMilliseconds(unixTimestamp).ToLocalTime(); return convertedTime; } public static string NumberToArab(int number) { switch (number) { case 0: return "0"; case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; case 6: return "VI"; } return ""; } /// /// 获取凌晨时间戳 单位s /// /// /// public static long GetMidnightTimestamp(DateTimeKind kind = DateTimeKind.Local) { DateTime now = DateTime.Now; DateTime midnight = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, kind); DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = midnight.ToUniversalTime() - epoch; return (long)timeSpan.TotalSeconds; } public static T DeepCopy(T obj) { using (var memoryStream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, obj); memoryStream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(memoryStream); } } } //UtilTools }