UtilTools.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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 + "m";
  516. }
  517. if (number > 100000)
  518. {
  519. float n = number / 1000f;
  520. string str = "";
  521. str = GetTargetDecimalPlaceStr((int)n);
  522. return str + "k";
  523. }
  524. return number.ToString();
  525. }
  526. public static string ToStringEx(this int number)
  527. {
  528. // if (number > 1000000000000)
  529. // {
  530. // float n = number / 1000000000000f;
  531. // string str = "";
  532. // str = GetTargetDecimalPlaceStr((int)n);
  533. // return str + "t";
  534. // }
  535. //
  536. // if (number > 1000000000)
  537. // {
  538. // float n = number / 1000000000f;
  539. // string str = "";
  540. // str = GetTargetDecimalPlaceStr((int)n);
  541. // return str + "b";
  542. // }
  543. if (number > 1000000)
  544. {
  545. float n = number / 10000f;
  546. string str = "";
  547. str = GetTargetDecimalPlaceStr((int)n);
  548. return str + "m";
  549. }
  550. if (number > 100000)
  551. {
  552. float n = number / 1000f;
  553. string str = "";
  554. str = GetTargetDecimalPlaceStr((int)n);
  555. return str + "k";
  556. }
  557. return number.ToString();
  558. // // if (isShowLongEx)
  559. // {
  560. // if (i >= 10000000000)
  561. // return (i / 1000000000) + "B";
  562. // else if (i >= 10000000)
  563. // return (i / 1000000) + "M";
  564. // else if (i >= 10000)
  565. // return (i / 1000) + "K";
  566. // }
  567. //
  568. // return i.ToString();
  569. }
  570. #endif
  571. /// <summary>
  572. /// 时间(秒)转换位小时分钟秒
  573. /// </summary>
  574. /// <param name="miao"></param>
  575. /// <returns></returns>
  576. public static string TimeToHSM(long miao)
  577. {
  578. long fen = miao / 60;
  579. miao = miao % 60;
  580. long xiaoShi = fen / 60;
  581. long tian = xiaoShi / 24;
  582. xiaoShi = xiaoShi % 24;
  583. fen = fen % 60;
  584. if (tian > 0)
  585. {
  586. return $"{tian}天{xiaoShi}小时";
  587. }
  588. else
  589. {
  590. if (xiaoShi <= 0 && fen <= 59)
  591. {
  592. return $"{fen}分{miao}秒";
  593. }
  594. else
  595. {
  596. return $"{xiaoShi}小时{fen}分";
  597. }
  598. }
  599. }
  600. /// <summary>
  601. /// 时间(秒)转换位小时分钟秒
  602. /// </summary>
  603. /// <param name="miao"></param>
  604. /// <returns></returns>
  605. public static string TimeToHSM1(long miao)
  606. {
  607. long fen = miao / 60;
  608. miao = miao % 60;
  609. long xiaoShi = fen / 60;
  610. long tian = xiaoShi / 24;
  611. xiaoShi = xiaoShi % 24;
  612. fen = fen % 60;
  613. if (tian <= 0 && xiaoShi <= 0)
  614. {
  615. return $"{fen}分钟";
  616. }
  617. else if (tian <= 0 && xiaoShi > 0)
  618. {
  619. return $"{xiaoShi}小时";
  620. }
  621. else if (tian >= 1)
  622. {
  623. return $"{tian}天";
  624. }
  625. return "";
  626. }
  627. public static string GeiLxTime(long miao)
  628. {
  629. long fen = miao / 60;
  630. miao = miao % 60;
  631. long xiaoShi = fen / 60;
  632. long tian = xiaoShi / 24;
  633. xiaoShi = xiaoShi % 24;
  634. fen = fen % 60;
  635. if (tian <= 0 && xiaoShi <= 0)
  636. {
  637. return $"离线{fen}分钟";
  638. }
  639. else if (tian <= 0 && xiaoShi > 0)
  640. {
  641. return $"离线{xiaoShi}小时";
  642. }
  643. else if (tian >= 1 && tian <= 7)
  644. {
  645. return $"离线{tian}天";
  646. }
  647. else if (tian > 7)
  648. {
  649. return "离线七天以上";
  650. }
  651. return "";
  652. }
  653. /// <summary>
  654. /// 类型1 :小于1天后显示分和秒
  655. /// </summary>
  656. /// <param name="miao"></param>
  657. /// <param name="type1"></param>
  658. /// <returns></returns>
  659. public static string TimeToHSM(long miao, int type1)
  660. {
  661. long fen = miao / 60;
  662. miao = miao % 60;
  663. long xiaoShi = fen / 60;
  664. long tian = xiaoShi / 24;
  665. xiaoShi = xiaoShi % 24;
  666. fen = fen % 60;
  667. if (tian > 0)
  668. {
  669. return $"{tian}天{xiaoShi}小时";
  670. }
  671. else
  672. {
  673. string key = "";
  674. switch (type1)
  675. {
  676. case 1:
  677. return $"{fen}分{miao}秒";
  678. break;
  679. default:
  680. break;
  681. }
  682. return key;
  683. }
  684. }
  685. /// <summary>获取秒级别时间戳(10位)</summary>
  686. public static long GetTimestampToSeconds()
  687. {
  688. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  689. return Convert.ToInt64(ts.TotalSeconds);
  690. }
  691. /// <summary>获取毫秒级别时间戳(13位)</summary>
  692. public static long GetTimeStampToMilliseconds()
  693. {
  694. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  695. return Convert.ToInt64(ts.TotalMilliseconds);
  696. }
  697. public static long GetTimestampToSeconds(int value)
  698. {
  699. DateTime dateTime = new DateTime(value, DateTimeKind.Utc);
  700. TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  701. return Convert.ToInt64(ts.TotalSeconds);
  702. }
  703. /// <summary>
  704. /// 时间戳转时间结构 秒
  705. /// </summary>
  706. /// <param name="unixTimestamp"></param>
  707. /// <returns></returns>
  708. public static DateTime ConvertUnixTimestamp(double unixTimestamp)
  709. {
  710. DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  711. DateTime convertedTime = unixStartTime.AddSeconds(unixTimestamp).ToLocalTime();
  712. return convertedTime;
  713. }
  714. /// <summary>
  715. ///时间戳转时间结构 毫秒
  716. /// </summary>
  717. /// <param name="unixTimestamp"></param>
  718. /// <returns></returns>
  719. public static DateTime ConvertUnixTimestampForMillis(double unixTimestamp)
  720. {
  721. DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  722. DateTime convertedTime = unixStartTime.AddMilliseconds(unixTimestamp).ToLocalTime();
  723. return convertedTime;
  724. }
  725. public static string NumberToArab(int number)
  726. {
  727. switch (number)
  728. {
  729. case 0: return "0";
  730. case 1: return "I";
  731. case 2: return "II";
  732. case 3: return "III";
  733. case 4: return "IV";
  734. case 5: return "V";
  735. case 6: return "VI";
  736. }
  737. return "";
  738. }
  739. /// <summary>
  740. /// 获取凌晨时间戳 单位s
  741. /// </summary>
  742. /// <param name="kind"></param>
  743. /// <returns></returns>
  744. public static long GetMidnightTimestamp(DateTimeKind kind = DateTimeKind.Local)
  745. {
  746. DateTime now = DateTime.Now;
  747. DateTime midnight = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, kind);
  748. DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  749. TimeSpan timeSpan = midnight.ToUniversalTime() - epoch;
  750. return (long)timeSpan.TotalSeconds;
  751. }
  752. public static T DeepCopy<T>(T obj)
  753. {
  754. using (var memoryStream = new MemoryStream())
  755. {
  756. var formatter = new BinaryFormatter();
  757. formatter.Serialize(memoryStream, obj);
  758. memoryStream.Seek(0, SeekOrigin.Begin);
  759. return (T)formatter.Deserialize(memoryStream);
  760. }
  761. }
  762. public static T GetRandomByWeight<T>(List<T> items, int[] weights)
  763. {
  764. if (items.Count != weights.Length)
  765. {
  766. LogTool.Error("权重和数组长度不一致");
  767. }
  768. int totalWeight = weights.Sum();
  769. Random random = new Random();
  770. int randomValue = random.Next(0, totalWeight);
  771. int currentWeight = 0;
  772. for (int i = 0; i < items.Count; i++)
  773. {
  774. currentWeight += weights[i];
  775. if (randomValue < currentWeight)
  776. return items[i];
  777. }
  778. // 理论上不会到达这里,但为了安全返回最后一个元素
  779. return items[items.Count - 1];
  780. }
  781. public static T GetRandomByWeight<T>(List<T> items, float[] weights)
  782. {
  783. if (items.Count != weights.Length)
  784. {
  785. LogTool.Error("权重和数组长度不一致");
  786. }
  787. float totalWeight = weights.Sum();
  788. Random random = new Random();
  789. float randomValue = (float)(random.NextDouble() * totalWeight);
  790. float currentWeight = 0;
  791. for (int i = 0; i < items.Count; i++)
  792. {
  793. currentWeight += weights[i];
  794. if (randomValue < currentWeight)
  795. return items[i];
  796. }
  797. // 理论上不会到达这里,但为了安全返回最后一个元素
  798. return items[items.Count - 1];
  799. }
  800. // 计算每个权重的概率
  801. public static List<float> CalculateProbabilities(List<float> weights)
  802. {
  803. List<float> probabilities = new List<float>();
  804. float totalWeight = 0f;
  805. // 计算总权重
  806. foreach (float weight in weights)
  807. {
  808. totalWeight += weight;
  809. }
  810. // 防止除以零
  811. if (totalWeight == 0)
  812. {
  813. Debug.LogWarning("总权重为 0,无法计算概率!");
  814. return probabilities;
  815. }
  816. // 计算每个权重的概率
  817. foreach (float weight in weights)
  818. {
  819. float probability = weight / totalWeight;
  820. probabilities.Add(probability);
  821. }
  822. return probabilities;
  823. }
  824. // 计算每个权重的概率
  825. public static List<float> CalculateProbabilities(List<int> weights)
  826. {
  827. List<float> probabilities = new List<float>();
  828. float totalWeight = 0f;
  829. // 计算总权重
  830. foreach (float weight in weights)
  831. {
  832. totalWeight += weight;
  833. }
  834. // 防止除以零
  835. if (totalWeight == 0)
  836. {
  837. Debug.LogWarning("总权重为 0,无法计算概率!");
  838. return probabilities;
  839. }
  840. // 计算每个权重的概率
  841. foreach (float weight in weights)
  842. {
  843. float probability = weight / totalWeight;
  844. probabilities.Add(probability);
  845. }
  846. return probabilities;
  847. }
  848. public static string GetString(string a, float[] b)
  849. {
  850. if (a == null || a == "" || b == null)
  851. return a;
  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. public static string GetString(string a, string[] b)
  862. {
  863. if (a == null || a == "" || b == null)
  864. return a;
  865. for (int i = 0; i < b.Length; i++)
  866. {
  867. string d = b[i].ToString();
  868. string c = "{" + i + "}";
  869. if (a.Contains(c))
  870. a = a.Replace(c, d);
  871. }
  872. return a;
  873. }
  874. public static string GetString(string a, int[] b)
  875. {
  876. if (a == null || a == "")
  877. return "null";
  878. for (int i = 0; i < b.Length; i++)
  879. {
  880. string d = b[i].ToString();
  881. string c = "{" + i + "}";
  882. if (a.Contains(c))
  883. a = a.Replace(c, d);
  884. }
  885. return a;
  886. }
  887. }
  888. //UtilTools
  889. }