| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866 | using System;using System.Collections.Generic;using System.Globalization;using System.Net;using System.Text;using System.Text.RegularExpressions;#if !COMBAT_SERVERusing UnityEngine;#endifusing System.IO;using System.Runtime.Serialization.Formatters.Binary;#if !COMBAT_SERVERusing UnityEngine.Profiling;#endifusing System.Security.Cryptography;using Fort23.UTool;namespace Utility{    public static class UtilTools    {#if !COMBAT_SERVER        public static List<GameObject> allDontDestroyOnLoad = new List<GameObject>();#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();        }        // /// <summary>        // /// 获取描述文本        // /// </summary>        // /// <param name="a"></param>        // /// <param name="b"></param>        // /// <returns></returns>        // 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;        // }                /// <summary>        /// 获取描述文本        /// </summary>        /// <param name="a"></param>        /// <param name="b"></param>        /// <returns></returns>        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;        }        /// <summary>        /// 获取描述文本        /// </summary>        /// <param name="a"></param>        /// <param name="b"></param>        /// <returns></returns>        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<AndroidJavaObject>("currentActivity");            AndroidJavaObject packageManager = context.Call<AndroidJavaObject>("getPackageManager");            string packageName = context.Call<string>("getPackageName");            int flags = packageManager.GetStatic<int>("GET_SIGNATURES");            AndroidJavaObject packageInfo =                packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, flags);            AndroidJavaObject[] signatures = packageInfo.Get<AndroidJavaObject[]>("signatures");            // Get the first signature (assuming only one signature)            AndroidJavaObject signature = signatures[0];            // Convert signature to bytes            byte[] signatureBytes = signature.Call<byte[]>("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        }        /// <summary>        /// 正则匹配        /// </summary>        /// <param name="str"></param>        /// <param name="data">"mydata|mydata|"</param>        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);        }        /// <summary>        /// 设置对象的层        /// </summary>        /// <param name="layerName"></param>        /// <param name="obj"></param>        /// <param name="isChild"></param>        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;            }        }        /// <summary>        /// 设置对象的层        /// </summary>        /// <param name="layerName"></param>        /// <param name="obj"></param>        /// <param name="isChild"></param>        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        /// <summary>        /// 获取场景中全部对象        /// </summary>        /// <typeparam name="T"></typeparam>        /// <returns></returns>        public static List<T> GetAllSceneObj<T>()        {            List<T> ts = new List<T>();            //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;        //}        /// <summary>        private static void AddObjcet<T>(List<T> 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<T>(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();        // }        /// <summary>        /// 获取目标小数位的str        /// </summary>        /// <param name="n"></param>        /// <returns></returns>        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);        }        /// <summary>        /// 四舍五入到整数        /// </summary>        /// <param name="value"></param>        /// <returns></returns>        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        /// <summary>        /// 时间(秒)转换位小时分钟秒        /// </summary>        /// <param name="miao"></param>        /// <returns></returns>        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}分";                }            }        }                        /// <summary>        /// 时间(秒)转换位小时分钟秒        /// </summary>        /// <param name="miao"></param>        /// <returns></returns>        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 "";        }        /// <summary>        ///   类型1 :小于1天后显示分和秒        /// </summary>        /// <param name="miao"></param>        /// <param name="type1"></param>        /// <returns></returns>        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;            }        }        /// <summary>获取秒级别时间戳(10位)</summary>        public static long GetTimestampToSeconds()        {            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);            return Convert.ToInt64(ts.TotalSeconds);        }        /// <summary>获取毫秒级别时间戳(13位)</summary>        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);        }        /// <summary>        /// 时间戳转时间结构 秒        /// </summary>        /// <param name="unixTimestamp"></param>        /// <returns></returns>        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;        }        /// <summary>        ///时间戳转时间结构 毫秒        /// </summary>        /// <param name="unixTimestamp"></param>        /// <returns></returns>        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 "";        }        /// <summary>        /// 获取凌晨时间戳 单位s        /// </summary>        /// <param name="kind"></param>        /// <returns></returns>        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>(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}
 |