12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025 |
- 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.Linq;
- using System.Runtime.Serialization.Formatters.Binary;
- #if !COMBAT_SERVER
- using UnityEngine.Profiling;
- #endif
- using System.Security.Cryptography;
- using Fort23.UTool;
- using Random = System.Random;
- 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;
- private static long startGUID;
- 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 long GetLOGGUID()
- {
- startGUID++;
- return startGUID;
- }
- // /// <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);
- }
- }
-
- public static T GetRandomByWeight<T>(List<T> items, int[] weights)
- {
- if (items.Count != weights.Length)
- {
- LogTool.Error("权重和数组长度不一致");
- }
- int totalWeight = weights.Sum();
- Random random = new Random();
- int randomValue = random.Next(0, totalWeight);
- int currentWeight = 0;
- for (int i = 0; i < items.Count; i++)
- {
- currentWeight += weights[i];
- if (randomValue < currentWeight)
- return items[i];
- }
- // 理论上不会到达这里,但为了安全返回最后一个元素
- return items[items.Count - 1];
- }
-
- public static T GetRandomByWeight<T>(List<T> items, float[] weights)
- {
-
- if (items.Count != weights.Length)
- {
- LogTool.Error("权重和数组长度不一致");
- }
- float totalWeight = weights.Sum();
- Random random = new Random();
- float randomValue = (float)(random.NextDouble() * totalWeight);
- float currentWeight = 0;
- for (int i = 0; i < items.Count; i++)
- {
- currentWeight += weights[i];
- if (randomValue < currentWeight)
- return items[i];
- }
- // 理论上不会到达这里,但为了安全返回最后一个元素
- return items[items.Count - 1];
- }
-
- // 计算每个权重的概率
- public static List<float> CalculateProbabilities(List<float> weights)
- {
- List<float> probabilities = new List<float>();
- float totalWeight = 0f;
- // 计算总权重
- foreach (float weight in weights)
- {
- totalWeight += weight;
- }
- // 防止除以零
- if (totalWeight == 0)
- {
- Debug.LogWarning("总权重为 0,无法计算概率!");
- return probabilities;
- }
- // 计算每个权重的概率
- foreach (float weight in weights)
- {
- float probability = weight / totalWeight;
- probabilities.Add(probability);
- }
- return probabilities;
- }
-
- // 计算每个权重的概率
- public static List<float> CalculateProbabilities(List<int> weights)
- {
- List<float> probabilities = new List<float>();
- float totalWeight = 0f;
- // 计算总权重
- foreach (float weight in weights)
- {
- totalWeight += weight;
- }
- // 防止除以零
- if (totalWeight == 0)
- {
- Debug.LogWarning("总权重为 0,无法计算概率!");
- return probabilities;
- }
- // 计算每个权重的概率
- foreach (float weight in weights)
- {
- float probability = weight / totalWeight;
- probabilities.Add(probability);
- }
- return probabilities;
- }
-
- public static string GetString(string a, float[] b)
- {
- if (a == null || a == "" || b == null)
- return a;
- for (int i = 0; i < b.Length; i++)
- {
- string d = b[i].ToString();
- string c = "{" + i + "}";
- if (a.Contains(c))
- a = a.Replace(c, d);
- }
- return a;
- }
- public static string GetString(string a, string[] b)
- {
- if (a == null || a == "" || b == null)
- return a;
- for (int i = 0; i < b.Length; i++)
- {
- string d = b[i].ToString();
- string c = "{" + i + "}";
- if (a.Contains(c))
- a = a.Replace(c, d);
- }
- return a;
- }
- public static string GetString(string a, int[] b)
- {
- if (a == null || a == "")
- return "null";
- for (int i = 0; i < b.Length; i++)
- {
- string d = b[i].ToString();
- string c = "{" + i + "}";
- if (a.Contains(c))
- a = a.Replace(c, d);
- }
- return a;
- }
-
- }
- //UtilTools
- }
|