UtilTools.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Net;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. #if !COMBAT_SERVER
  8. using UnityEngine;
  9. #endif
  10. using System.IO;
  11. using System.Linq;
  12. using System.Runtime.Serialization.Formatters.Binary;
  13. #if !COMBAT_SERVER
  14. using UnityEngine.Profiling;
  15. #endif
  16. using System.Security.Cryptography;
  17. using Fort23.UTool;
  18. using Random = System.Random;
  19. namespace Utility
  20. {
  21. public static class UtilTools
  22. {
  23. #if !COMBAT_SERVER
  24. public static List<GameObject> allDontDestroyOnLoad = new List<GameObject>();
  25. #endif
  26. private static int m_seed = 0;
  27. private static StringBuilder sb;
  28. private static long startGUID;
  29. public static long oneDay = 86400000;
  30. public static int GenerateSeed()
  31. {
  32. m_seed++;
  33. return m_seed;
  34. }
  35. public static float FrameToDuration(int frame)
  36. {
  37. return frame * 0.02f;
  38. }
  39. public static string GetGUID()
  40. {
  41. System.Guid guid = new Guid();
  42. guid = Guid.NewGuid();
  43. string str = guid.ToString();
  44. return str;
  45. }
  46. #if !COMBAT_SERVER
  47. public static void SetDontDestroyOnLoad(GameObject go)
  48. {
  49. if (allDontDestroyOnLoad.Contains(go))
  50. {
  51. return;
  52. }
  53. GameObject.DontDestroyOnLoad(go);
  54. allDontDestroyOnLoad.Add(go);
  55. }
  56. public static int DurationToFrame(float duration)
  57. {
  58. return (int)(duration / Time.fixedDeltaTime);
  59. }
  60. #endif
  61. // public static int RoundToInt(float value)
  62. // {
  63. // return (int)System.Math.Round(value);
  64. // }
  65. #if !COMBAT_SERVER
  66. public static string CombineString(params string[] strs)
  67. {
  68. StringBuilder sb = new StringBuilder();
  69. for (int i = 0; i < strs.Length; i++)
  70. {
  71. sb.Append(strs[i]);
  72. }
  73. return sb.ToString();
  74. }
  75. public static string CombineString(params object[] strs)
  76. {
  77. if (sb == null)
  78. {
  79. sb = new StringBuilder();
  80. }
  81. sb.Clear();
  82. //StringBuilder sb = new StringBuilder();
  83. for (int i = 0; i < strs.Length; i++)
  84. {
  85. sb.Append(strs[i]);
  86. }
  87. return sb.ToString();
  88. }
  89. public static long GetLOGGUID()
  90. {
  91. startGUID++;
  92. return startGUID;
  93. }
  94. // /// <summary>
  95. // /// 获取描述文本
  96. // /// </summary>
  97. // /// <param name="a"></param>
  98. // /// <param name="b"></param>
  99. // /// <returns></returns>
  100. // public static string GetDscString(string a, float[] b)
  101. // {
  102. // if (a == "")
  103. // return "";
  104. // for (int i = 0; i < b?.Length; i++)
  105. // {
  106. // string d = b[i].ToString();
  107. // string c = "{" + i + "}";
  108. // a = a.Replace(c, d);
  109. // }
  110. //
  111. // return a;
  112. // }
  113. /// <summary>
  114. /// 获取描述文本
  115. /// </summary>
  116. /// <param name="a"></param>
  117. /// <param name="b"></param>
  118. /// <returns></returns>
  119. public static string GetDscString(string a, float[] b)
  120. {
  121. if (a == "")
  122. return "";
  123. for (int i = 0; i < b?.Length; i++)
  124. {
  125. string d = b[i].ToString("0.##");
  126. string c = "{" + i + "}";
  127. a = a.Replace(c, d);
  128. }
  129. return a;
  130. }
  131. /// <summary>
  132. /// 获取描述文本
  133. /// </summary>
  134. /// <param name="a"></param>
  135. /// <param name="b"></param>
  136. /// <returns></returns>
  137. public static string GetDscString(string a, string[] b)
  138. {
  139. if (a == "")
  140. return "";
  141. for (int i = 0; i < b?.Length; i++)
  142. {
  143. string d = b[i].ToString();
  144. string c = "{" + i + "}";
  145. a = a.Replace(c, d);
  146. }
  147. return a;
  148. }
  149. public static string GetSignaturesInfo()
  150. {
  151. #if UNITY_ANDROID&&!UNITY_EDITOR
  152. AndroidJavaClass contextClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  153. AndroidJavaObject context = contextClass.GetStatic<AndroidJavaObject>("currentActivity");
  154. AndroidJavaObject packageManager = context.Call<AndroidJavaObject>("getPackageManager");
  155. string packageName = context.Call<string>("getPackageName");
  156. int flags = packageManager.GetStatic<int>("GET_SIGNATURES");
  157. AndroidJavaObject packageInfo =
  158. packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, flags);
  159. AndroidJavaObject[] signatures = packageInfo.Get<AndroidJavaObject[]>("signatures");
  160. // Get the first signature (assuming only one signature)
  161. AndroidJavaObject signature = signatures[0];
  162. // Convert signature to bytes
  163. byte[] signatureBytes = signature.Call<byte[]>("toByteArray");
  164. // Compute SHA256 hash
  165. SHA256 sha256 = SHA256.Create();
  166. byte[] hashBytes = sha256.ComputeHash(signatureBytes);
  167. // Convert bytes to hex string
  168. StringBuilder builder = new StringBuilder();
  169. for (int i = 0; i < hashBytes.Length; i++)
  170. {
  171. // Debug.Log(hashBytes[i].ToString("x2").ToUpperInvariant());
  172. builder.Append(hashBytes[i].ToString("X2"));
  173. if (i < hashBytes.Length - 1)
  174. {
  175. builder.Append(":");
  176. }
  177. }
  178. string sha256Signature = builder.ToString();
  179. return sha256Signature;
  180. #else
  181. return "";
  182. #endif
  183. }
  184. /// <summary>
  185. /// 正则匹配
  186. /// </summary>
  187. /// <param name="str"></param>
  188. /// <param name="data">"mydata|mydata|"</param>
  189. public static bool MatchingMouna(ref string str, string data)
  190. {
  191. MatchCollection m = Regex.Matches(str, "(" + data + ")", RegexOptions.Multiline);
  192. for (int i = 0; i < m.Count; i++)
  193. {
  194. string m1 = Regex.Replace(m[i].ToString(), "\\$", "\\$");
  195. m1 = Regex.Replace(m1, "\\^", "\\^");
  196. string xingxing = "";
  197. for (int j = 0; j < m1.Length; j++)
  198. xingxing += "*";
  199. str = Regex.Replace(str, m1, xingxing);
  200. }
  201. if (m.Count > 0)
  202. {
  203. return true;
  204. }
  205. else
  206. {
  207. return false;
  208. }
  209. //LogManager.Instance.Log(str + " " + data);
  210. }
  211. /// <summary>
  212. /// 设置对象的层
  213. /// </summary>
  214. /// <param name="layerName"></param>
  215. /// <param name="obj"></param>
  216. /// <param name="isChild"></param>
  217. public static void SetGameObjctLayer(string layerName, GameObject obj, bool isChild = true)
  218. {
  219. int layerIdx = LayerMask.NameToLayer(layerName);
  220. if (isChild)
  221. SetChildLayer(layerIdx, obj.transform);
  222. else
  223. {
  224. obj.layer = layerIdx;
  225. }
  226. }
  227. /// <summary>
  228. /// 设置对象的层
  229. /// </summary>
  230. /// <param name="layerName"></param>
  231. /// <param name="obj"></param>
  232. /// <param name="isChild"></param>
  233. public static void SetGameObjctLayer(int layer, GameObject obj, bool isChild = true)
  234. {
  235. //int layerIdx = LayerMask.NameToLayer(layerName);
  236. if (isChild)
  237. SetChildLayer(layer, obj.transform);
  238. else
  239. {
  240. obj.layer = layer;
  241. }
  242. }
  243. private static void SetChildLayer(int layerIdx, Transform obj)
  244. {
  245. obj.gameObject.layer = layerIdx;
  246. for (int i = 0; i < obj.childCount; i++)
  247. {
  248. SetChildLayer(layerIdx, obj.GetChild(i));
  249. }
  250. }
  251. public static IPEndPoint CombineIPAddress(string host, int port)
  252. {
  253. return new IPEndPoint(IPAddress.Parse(host), port);
  254. }
  255. public static bool IsStringLetterAndNumber(string content)
  256. {
  257. if (content.Length == 0)
  258. {
  259. return false;
  260. }
  261. int asciiCount = Regex.Matches(content, "[a-zA-Z0-9]").Count;
  262. return (content.Length > asciiCount) ? false : true;
  263. }
  264. public static bool IsArrayValid(object array)
  265. {
  266. if (array == null || !(array is Array) || (array as Array).Length == 0)
  267. {
  268. return false;
  269. }
  270. return true;
  271. }
  272. public static Texture2D GetTexture(string path)
  273. {
  274. if (string.IsNullOrEmpty(path))
  275. return null;
  276. if (!File.Exists(path))
  277. return null;
  278. byte[] data = File.ReadAllBytes(path);
  279. Texture2D textrue = new Texture2D(512, 512);
  280. textrue.LoadImage(data);
  281. return textrue;
  282. }
  283. private static string m_bannedWorlds;
  284. public static bool IsBannedWord(string rolename)
  285. {
  286. return false;
  287. }
  288. #if UNITY_EDITOR
  289. /// <summary>
  290. /// 获取场景中全部对象
  291. /// </summary>
  292. /// <typeparam name="T"></typeparam>
  293. /// <returns></returns>
  294. public static List<T> GetAllSceneObj<T>()
  295. {
  296. List<T> ts = new List<T>();
  297. //HierarchyProperty.
  298. //EditorSceneManager.
  299. GameObject[] go = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
  300. //LogTool.Log(go.Length);
  301. AddObjcet(ts, go);
  302. go = Utility.UtilTools.allDontDestroyOnLoad.ToArray();
  303. AddObjcet(ts, go);
  304. return ts;
  305. }
  306. //public static string GetModelName(GlobalConfig.LevelType _type, MapUnit unit)
  307. //{
  308. // string str =FixationString.empty;
  309. // switch (unit)
  310. // {
  311. // case MapUnit.Wall:
  312. // str = _type.SplitToString() + "_Wall_";
  313. // break;
  314. // case MapUnit.Coin:
  315. // return _type.SplitToString() + "_Seed";
  316. // case MapUnit.Gate:
  317. // return _type.SplitToString() + "_Gate";
  318. // case MapUnit.Player:
  319. // return "Player";
  320. // case MapUnit.WallVisible:
  321. // return _type.SplitToString() + "_WallInvisible";
  322. // case MapUnit.CoinVisible:
  323. // return _type.SplitToString() + "SeedInvisible";
  324. // case MapUnit.BlockLight:
  325. // case MapUnit.BlockBalance:
  326. // case MapUnit.BlockNormal:
  327. // case MapUnit.BlockSleep:
  328. // case MapUnit.BlockGravity:
  329. // return "Block" + _type.SplitToString();
  330. // case MapUnit.Wall_DestroyAble:
  331. // return "Wall_DestroyAble";
  332. // }
  333. // return str;
  334. //}
  335. /// <summary>
  336. private static void AddObjcet<T>(List<T> ts, GameObject[] go)
  337. {
  338. for (int i = 0; i < go.Length; i++)
  339. {
  340. if (!go[i])
  341. continue;
  342. //if (!go[i].gameObject)
  343. // continue;
  344. T[] objs = go[i].transform.GetComponentsInChildren<T>(true);
  345. for (int j = 0; j < objs.Length; j++)
  346. {
  347. ts.Add(objs[j]);
  348. }
  349. }
  350. }
  351. #endif
  352. public static string GetMD5(string inStr)
  353. {
  354. MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
  355. byte[] InBytes = Encoding.UTF8.GetBytes(inStr);
  356. byte[] OutBytes = md5.ComputeHash(InBytes);
  357. string OutString = "";
  358. for (int i = 0; i < OutBytes.Length; i++)
  359. {
  360. OutString += OutBytes[i].ToString("x2");
  361. }
  362. //LogTool.Log(OutString);
  363. if (OutString.Length > 8) OutString = OutString.Substring(0, 8);
  364. return OutString;
  365. }
  366. // DES加密
  367. public static string DESEncrypt(string pToEncrypt, string sKey)
  368. {
  369. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  370. byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
  371. // if (sKey.Length > 8) sKey = sKey.Substring(0, 8);
  372. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  373. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  374. MemoryStream ms = new MemoryStream();
  375. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  376. cs.Write(inputByteArray, 0, inputByteArray.Length);
  377. cs.FlushFinalBlock();
  378. StringBuilder ret = new StringBuilder();
  379. foreach (byte b in ms.ToArray())
  380. {
  381. ret.AppendFormat("{0:X2}", b);
  382. }
  383. ret.ToString();
  384. //LogTool.Log(inputByteArray.Length + " 加密后" + ret.SplitToString().Length);
  385. return ret.ToString();
  386. }
  387. // DES解密
  388. public static string DESDecrypt(string pToDecrypt, string sKey)
  389. {
  390. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  391. byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
  392. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  393. {
  394. int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
  395. inputByteArray[x] = (byte)i;
  396. }
  397. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  398. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  399. MemoryStream ms = new MemoryStream();
  400. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  401. cs.Write(inputByteArray, 0, inputByteArray.Length);
  402. cs.FlushFinalBlock();
  403. StringBuilder ret = new StringBuilder();
  404. return System.Text.Encoding.UTF8.GetString(ms.ToArray());
  405. }
  406. public static string BASE64_Decode(string data)
  407. {
  408. byte[] bytes = Convert.FromBase64String(data);
  409. return Encoding.UTF8.GetString(bytes);
  410. }
  411. public static string GetMD5HashFromFile(byte[] data)
  412. {
  413. try
  414. {
  415. // FileStream file = new FileStream(filename,FileMode.Open);
  416. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  417. byte[] retVal = md5.ComputeHash(data);
  418. StringBuilder sb = new StringBuilder();
  419. for (int i = 0; i < retVal.Length; i++)
  420. {
  421. sb.Append(retVal[i].ToString("x2"));
  422. }
  423. return sb.ToString();
  424. }
  425. catch (System.Exception ex)
  426. {
  427. LogTool.Log("错误信息:" + ex);
  428. return null;
  429. }
  430. }
  431. public static string FormatTwoTime(int totalSeconds)
  432. {
  433. int minutes = totalSeconds / 60;
  434. string mm = minutes < 10f ? "0" + minutes : minutes.ToString();
  435. int seconds = (totalSeconds - (minutes * 60));
  436. string ss = seconds < 10 ? "0" + seconds : seconds.ToString();
  437. return string.Format("{0}:{1}", mm, ss);
  438. }
  439. // public static string ToStringEx(this long i)
  440. // {
  441. // // if (isShowLongEx)
  442. // {
  443. // if (i >= 10000000000)
  444. // return (i / 1000000000) + "B";
  445. // else if (i >= 10000000)
  446. // return (i / 1000000) + "M";
  447. // else if (i >= 10000)
  448. // return (i / 1000) + "K";
  449. // }
  450. //
  451. // return i.ToString();
  452. // }
  453. /// <summary>
  454. /// 获取目标小数位的str
  455. /// </summary>
  456. /// <param name="n"></param>
  457. /// <returns></returns>
  458. public static string GetTargetDecimalPlaceStr(int n)
  459. {
  460. string str = "";
  461. if (n >= 100) //整数大于两位数保留一位小数
  462. {
  463. int n1 = (int)(n * 10);
  464. n = n1 / 10;
  465. str = n.ToString(CultureInfo.InvariantCulture);
  466. }
  467. else
  468. {
  469. //保留两位小数
  470. int n1 = (int)(n * 100);
  471. n = n1 / 100;
  472. str = n.ToString(CultureInfo.InvariantCulture);
  473. }
  474. return str;
  475. }
  476. public static long Round(this float number)
  477. {
  478. return (long)Math.Ceiling(number);
  479. }
  480. /// <summary>
  481. /// 四舍五入到整数
  482. /// </summary>
  483. /// <param name="value"></param>
  484. /// <returns></returns>
  485. public static int RoundToInt(this float value)
  486. {
  487. // float tempValue = value.Round(0);
  488. // int finalValue = Mathf.FloorToInt(tempValue);
  489. Math.Ceiling(value);
  490. return (int)Math.Ceiling(value);
  491. ;
  492. }
  493. public static string ToStringEx(this long number)
  494. {
  495. // if (number > 1000000000000)
  496. // {
  497. // float n = number / 1000000000000f;
  498. // string str = "";
  499. // str = GetTargetDecimalPlaceStr((int)n);
  500. // return str + "t";
  501. // }
  502. //
  503. // if (number > 1000000000)
  504. // {
  505. // float n = number / 1000000000f;
  506. // string str = "";
  507. // str = GetTargetDecimalPlaceStr((int)n);
  508. // return str + "b";
  509. // }
  510. if (number > 1000000)
  511. {
  512. float n = number / 10000f;
  513. string str = "";
  514. str = GetTargetDecimalPlaceStr((int)n);
  515. return str + "万";
  516. }
  517. if (number > 100000)
  518. {
  519. float n = number / 1000f;
  520. string str = "";
  521. str = GetTargetDecimalPlaceStr((int)n);
  522. return str + "千";
  523. }
  524. return number.ToString();
  525. }
  526. public static string ToStringEx(this int number)
  527. {
  528. if (number > 1000000)
  529. {
  530. float n = number / 10000f;
  531. string str = "";
  532. str = GetTargetDecimalPlaceStr((int)n);
  533. return str + "万";
  534. }
  535. if (number > 100000)
  536. {
  537. float n = number / 1000f;
  538. string str = "";
  539. str = GetTargetDecimalPlaceStr((int)n);
  540. return str + "千";
  541. }
  542. return number.ToString();
  543. }
  544. #endif
  545. /// <summary>
  546. /// 时间(秒)转换位小时分钟秒
  547. /// </summary>
  548. /// <param name="miao"></param>
  549. /// <returns></returns>
  550. public static string TimeToHSM(long miao)
  551. {
  552. long fen = miao / 60;
  553. miao = miao % 60;
  554. long xiaoShi = fen / 60;
  555. long tian = xiaoShi / 24;
  556. xiaoShi = xiaoShi % 24;
  557. fen = fen % 60;
  558. if (tian > 0)
  559. {
  560. return $"{tian}天{xiaoShi}小时";
  561. }
  562. else
  563. {
  564. if (xiaoShi <= 0 && fen <= 59)
  565. {
  566. return $"{fen}分{miao}秒";
  567. }
  568. else
  569. {
  570. return $"{xiaoShi}小时{fen}分";
  571. }
  572. }
  573. }
  574. /// <summary>
  575. /// 时间(秒)转换位小时分钟秒
  576. /// </summary>
  577. /// <param name="miao"></param>
  578. /// <returns></returns>
  579. public static string TimeToHSM1(long miao)
  580. {
  581. long fen = miao / 60;
  582. miao = miao % 60;
  583. long xiaoShi = fen / 60;
  584. long tian = xiaoShi / 24;
  585. xiaoShi = xiaoShi % 24;
  586. fen = fen % 60;
  587. if (tian <= 0 && xiaoShi <= 0)
  588. {
  589. return $"{fen}分钟";
  590. }
  591. else if (tian <= 0 && xiaoShi > 0)
  592. {
  593. return $"{xiaoShi}小时";
  594. }
  595. else if (tian >= 1)
  596. {
  597. return $"{tian}天";
  598. }
  599. return "";
  600. }
  601. public static string GeiLxTime(long miao)
  602. {
  603. long fen = miao / 60;
  604. miao = miao % 60;
  605. long xiaoShi = fen / 60;
  606. long tian = xiaoShi / 24;
  607. xiaoShi = xiaoShi % 24;
  608. fen = fen % 60;
  609. if (tian <= 0 && xiaoShi <= 0)
  610. {
  611. return $"离线{fen}分钟";
  612. }
  613. else if (tian <= 0 && xiaoShi > 0)
  614. {
  615. return $"离线{xiaoShi}小时";
  616. }
  617. else if (tian >= 1 && tian <= 7)
  618. {
  619. return $"离线{tian}天";
  620. }
  621. else if (tian > 7)
  622. {
  623. return "离线七天以上";
  624. }
  625. return "";
  626. }
  627. /// <summary>
  628. /// 类型1 :小于1天后显示分和秒
  629. /// </summary>
  630. /// <param name="miao"></param>
  631. /// <param name="type1"></param>
  632. /// <returns></returns>
  633. public static string TimeToHSM(long miao, int type1)
  634. {
  635. long fen = miao / 60;
  636. miao = miao % 60;
  637. long xiaoShi = fen / 60;
  638. long tian = xiaoShi / 24;
  639. xiaoShi = xiaoShi % 24;
  640. fen = fen % 60;
  641. if (tian > 0)
  642. {
  643. return $"{tian}天{xiaoShi}小时";
  644. }
  645. else
  646. {
  647. string key = "";
  648. switch (type1)
  649. {
  650. case 1:
  651. return $"{fen}分{miao}秒";
  652. break;
  653. default:
  654. break;
  655. }
  656. return key;
  657. }
  658. }
  659. /// <summary>获取秒级别时间戳(10位)</summary>
  660. public static long GetTimestampToSeconds()
  661. {
  662. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  663. return Convert.ToInt64(ts.TotalSeconds);
  664. }
  665. /// <summary>获取毫秒级别时间戳(13位)</summary>
  666. public static long GetTimeStampToMilliseconds()
  667. {
  668. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  669. return Convert.ToInt64(ts.TotalMilliseconds);
  670. }
  671. public static long GetTimestampToSeconds(int value)
  672. {
  673. DateTime dateTime = new DateTime(value, DateTimeKind.Utc);
  674. TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  675. return Convert.ToInt64(ts.TotalSeconds);
  676. }
  677. /// <summary>
  678. /// 时间戳转时间结构 秒
  679. /// </summary>
  680. /// <param name="unixTimestamp"></param>
  681. /// <returns></returns>
  682. public static DateTime ConvertUnixTimestamp(double unixTimestamp)
  683. {
  684. DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  685. DateTime convertedTime = unixStartTime.AddSeconds(unixTimestamp).ToLocalTime();
  686. return convertedTime;
  687. }
  688. /// <summary>
  689. ///时间戳转时间结构 毫秒
  690. /// </summary>
  691. /// <param name="unixTimestamp"></param>
  692. /// <returns></returns>
  693. public static DateTime ConvertUnixTimestampForMillis(double unixTimestamp)
  694. {
  695. DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  696. DateTime convertedTime = unixStartTime.AddMilliseconds(unixTimestamp).ToLocalTime();
  697. return convertedTime;
  698. }
  699. public static string NumberToArab(int number)
  700. {
  701. switch (number)
  702. {
  703. case 0: return "0";
  704. case 1: return "I";
  705. case 2: return "II";
  706. case 3: return "III";
  707. case 4: return "IV";
  708. case 5: return "V";
  709. case 6: return "VI";
  710. }
  711. return "";
  712. }
  713. /// <summary>
  714. /// 获取凌晨时间戳 单位s
  715. /// </summary>
  716. /// <param name="kind"></param>
  717. /// <returns></returns>
  718. public static long GetMidnightTimestamp(DateTimeKind kind = DateTimeKind.Local)
  719. {
  720. DateTime now = DateTime.Now;
  721. DateTime midnight = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, kind);
  722. DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  723. TimeSpan timeSpan = midnight.ToUniversalTime() - epoch;
  724. return (long)timeSpan.TotalSeconds;
  725. }
  726. public static T DeepCopy<T>(T obj)
  727. {
  728. using (var memoryStream = new MemoryStream())
  729. {
  730. var formatter = new BinaryFormatter();
  731. formatter.Serialize(memoryStream, obj);
  732. memoryStream.Seek(0, SeekOrigin.Begin);
  733. return (T)formatter.Deserialize(memoryStream);
  734. }
  735. }
  736. public static T GetRandomByWeight<T>(List<T> items, int[] weights)
  737. {
  738. if (items.Count != weights.Length)
  739. {
  740. LogTool.Error("权重和数组长度不一致");
  741. }
  742. int totalWeight = weights.Sum();
  743. Random random = new Random();
  744. int randomValue = random.Next(0, totalWeight);
  745. int currentWeight = 0;
  746. for (int i = 0; i < items.Count; i++)
  747. {
  748. currentWeight += weights[i];
  749. if (randomValue < currentWeight)
  750. return items[i];
  751. }
  752. // 理论上不会到达这里,但为了安全返回最后一个元素
  753. return items[items.Count - 1];
  754. }
  755. public static T GetRandomByWeight<T>(List<T> items, float[] weights)
  756. {
  757. if (items.Count != weights.Length)
  758. {
  759. LogTool.Error("权重和数组长度不一致");
  760. }
  761. float totalWeight = weights.Sum();
  762. Random random = new Random();
  763. float randomValue = (float)(random.NextDouble() * totalWeight);
  764. float currentWeight = 0;
  765. for (int i = 0; i < items.Count; i++)
  766. {
  767. currentWeight += weights[i];
  768. if (randomValue < currentWeight)
  769. return items[i];
  770. }
  771. // 理论上不会到达这里,但为了安全返回最后一个元素
  772. return items[items.Count - 1];
  773. }
  774. // 计算每个权重的概率
  775. public static List<float> CalculateProbabilities(List<float> weights)
  776. {
  777. List<float> probabilities = new List<float>();
  778. float totalWeight = 0f;
  779. // 计算总权重
  780. foreach (float weight in weights)
  781. {
  782. totalWeight += weight;
  783. }
  784. // 防止除以零
  785. if (totalWeight == 0)
  786. {
  787. Debug.LogWarning("总权重为 0,无法计算概率!");
  788. return probabilities;
  789. }
  790. // 计算每个权重的概率
  791. foreach (float weight in weights)
  792. {
  793. float probability = weight / totalWeight;
  794. probabilities.Add(probability);
  795. }
  796. return probabilities;
  797. }
  798. // 计算每个权重的概率
  799. public static List<float> CalculateProbabilities(List<int> weights)
  800. {
  801. List<float> probabilities = new List<float>();
  802. float totalWeight = 0f;
  803. // 计算总权重
  804. foreach (float weight in weights)
  805. {
  806. totalWeight += weight;
  807. }
  808. // 防止除以零
  809. if (totalWeight == 0)
  810. {
  811. Debug.LogWarning("总权重为 0,无法计算概率!");
  812. return probabilities;
  813. }
  814. // 计算每个权重的概率
  815. foreach (float weight in weights)
  816. {
  817. float probability = weight / totalWeight;
  818. probabilities.Add(probability);
  819. }
  820. return probabilities;
  821. }
  822. public static string GetString(string a, float[] b)
  823. {
  824. if (a == null || a == "" || b == null)
  825. return a;
  826. for (int i = 0; i < b.Length; i++)
  827. {
  828. string d = b[i].ToString();
  829. string c = "{" + i + "}";
  830. if (a.Contains(c))
  831. a = a.Replace(c, d);
  832. }
  833. return a;
  834. }
  835. public static string GetString(string a, string[] b)
  836. {
  837. if (a == null || a == "" || b == null)
  838. return a;
  839. for (int i = 0; i < b.Length; i++)
  840. {
  841. string d = b[i].ToString();
  842. string c = "{" + i + "}";
  843. if (a.Contains(c))
  844. a = a.Replace(c, d);
  845. }
  846. return a;
  847. }
  848. public static string GetString(string a, int[] b)
  849. {
  850. if (a == null || a == "")
  851. return "null";
  852. for (int i = 0; i < b.Length; i++)
  853. {
  854. string d = b[i].ToString();
  855. string c = "{" + i + "}";
  856. if (a.Contains(c))
  857. a = a.Replace(c, d);
  858. }
  859. return a;
  860. }
  861. }
  862. //UtilTools
  863. }