Util.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12. using Object = UnityEngine.Object;
  13. using Random = System.Random;
  14. using System.Net.Sockets;
  15. using System.Net.NetworkInformation;
  16. using UnityEngine.Events;
  17. using System.Threading.Tasks;
  18. namespace Base.Common
  19. {
  20. public class Util
  21. {
  22. public static int UID = 0;
  23. static string[] kSizeSuffix = new string[]
  24. {
  25. "B",
  26. "KB",
  27. "MB",
  28. "GB",
  29. "TB",
  30. "PB",
  31. };
  32. private static StringBuilder sTmpStringBuidler = new StringBuilder();
  33. private static Dictionary<string, Type> sPredefineComponentTypes = new Dictionary<string, Type>()
  34. {
  35. };
  36. public static void SetUID(int uid)
  37. {
  38. UID = uid;
  39. }
  40. public static string ColorToHex(Color32 color)
  41. {
  42. string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2");
  43. return hex;
  44. }
  45. /// <summary>
  46. /// HashToMD5Hex
  47. /// </summary>
  48. public static string HashToMD5Hex(string sourceStr)
  49. {
  50. byte[] Bytes = Encoding.UTF8.GetBytes(sourceStr);
  51. using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
  52. {
  53. byte[] result = md5.ComputeHash(Bytes);
  54. StringBuilder builder = new StringBuilder();
  55. for (int i = 0; i < result.Length; i++)
  56. builder.Append(result[i].ToString("x2"));
  57. return builder.ToString();
  58. }
  59. }
  60. public static string GetFileMD5(string filePath)
  61. {
  62. try
  63. {
  64. using (FileStream fs = new FileStream(filePath, FileMode.Open))
  65. {
  66. using (MD5 md5 = new MD5CryptoServiceProvider())
  67. {
  68. byte[] result = md5.ComputeHash(fs);
  69. StringBuilder sb = new StringBuilder();
  70. foreach (byte b in result)
  71. {
  72. sb.Append(b.ToString("x2"));
  73. }
  74. return sb.ToString();
  75. }
  76. }
  77. }
  78. catch (Exception e)
  79. {
  80. return string.Empty;
  81. }
  82. }
  83. public static string GetMD5(byte[] bytes)
  84. {
  85. using (MD5 md5 = new MD5CryptoServiceProvider())
  86. {
  87. byte[] result = md5.ComputeHash(bytes);
  88. StringBuilder sb = new StringBuilder();
  89. foreach (byte b in result)
  90. {
  91. sb.Append(b.ToString("x2"));
  92. }
  93. return sb.ToString();
  94. }
  95. }
  96. public static GameObject LoadGameObject(string path)
  97. {
  98. GameObject prefab;
  99. prefab = Resources.Load<GameObject>(path);
  100. if (!prefab)
  101. {
  102. Debug.LogError("未读取到prefab:" + path);
  103. return null;
  104. }
  105. return prefab;
  106. }
  107. public static GameObject Instantiate(string path, Vector3 pos = default, Quaternion rotation = default, Transform parent = null, bool active = true)
  108. {
  109. GameObject prefab;
  110. prefab = Resources.Load<GameObject>(path);
  111. if (!prefab)
  112. {
  113. Debug.LogError("未读取到prefab:" + path);
  114. return null;
  115. }
  116. GameObject gameObject = null;
  117. if (prefab != null)
  118. {
  119. gameObject = PoolManager.Instantiate(prefab, pos, rotation, parent);
  120. gameObject.SetActive(active);
  121. }
  122. else
  123. {
  124. Debug.LogError("PrefabPathError:" + path);
  125. }
  126. return gameObject;
  127. }
  128. /// <summary>
  129. /// 判断物体是否为空,主要给Lua调用
  130. /// </summary>
  131. /// <param name="o"></param>
  132. /// <returns></returns>
  133. public static bool IsObjectNull(Object o)
  134. {
  135. return o == null;
  136. }
  137. private static Type GetComponentType(string _compname)
  138. {
  139. if (string.IsNullOrEmpty(_compname))
  140. return null;
  141. Type t = null;
  142. if (sPredefineComponentTypes.ContainsKey(_compname))
  143. return sPredefineComponentTypes[_compname];
  144. Assembly assb = Assembly.GetExecutingAssembly(); //.GetExecutingAssembly();
  145. t = assb.GetType(_compname);
  146. if (null == t)
  147. {
  148. return null;
  149. }
  150. sPredefineComponentTypes[_compname] = t;
  151. return t;
  152. }
  153. public static Component GetComponentInChildren(GameObject _go, string _compname)
  154. {
  155. if (_go == null)
  156. return null;
  157. Type t = GetComponentType(_compname);
  158. if (null == t)
  159. {
  160. return null;
  161. }
  162. return _go.GetComponentInChildren(t);
  163. }
  164. public static Component GetComponentInChildren(Component _comp, string _compname)
  165. {
  166. if (_comp == null)
  167. return null;
  168. Type t = GetComponentType(_compname);
  169. if (null == t)
  170. {
  171. return null;
  172. }
  173. return _comp.GetComponentInChildren(t);
  174. }
  175. public static string GetReadableSize(long size)
  176. {
  177. long step = 1024;
  178. double filesize = size;
  179. int size_suffix_index = 0;
  180. while (filesize > step)
  181. {
  182. if (size_suffix_index >= kSizeSuffix.Length - 1)
  183. {
  184. size_suffix_index = kSizeSuffix.Length - 1;
  185. break;
  186. }
  187. ++size_suffix_index;
  188. filesize /= step;
  189. }
  190. return string.Format("{0:F2}{1}", filesize, kSizeSuffix[size_suffix_index]);
  191. }
  192. /// <summary>
  193. /// 打开URL
  194. /// </summary>
  195. /// <param name="url"></param>
  196. public static void OpenUrl(string url)
  197. {
  198. Application.OpenURL(url);
  199. }
  200. #region PlayerPrefs
  201. public static int GetInt(string key, int value = default(int))
  202. {
  203. return PlayerPrefs.GetInt(key, value);
  204. }
  205. public static bool HasKey(string key)
  206. {
  207. return PlayerPrefs.HasKey(key);
  208. }
  209. public static bool HasString(string key)
  210. {
  211. return PlayerPrefs.HasKey(key);
  212. }
  213. public static void SetInt(string key, int value = default(int))
  214. {
  215. PlayerPrefs.DeleteKey(key);
  216. PlayerPrefs.SetInt(key, value);
  217. }
  218. public static string GetString(string key, string value = default(string))
  219. {
  220. return PlayerPrefs.GetString(key, value);
  221. }
  222. /// <summary>
  223. /// 保存数据
  224. /// </summary>
  225. public static void SetString(string key, string value = default(string))
  226. {
  227. PlayerPrefs.DeleteKey(key);
  228. PlayerPrefs.SetString(key, value);
  229. }
  230. /// <summary>
  231. /// 删除数据
  232. /// </summary>
  233. public static void RemoveKey(string key)
  234. {
  235. PlayerPrefs.DeleteKey(key);
  236. }
  237. public static bool CheckKeyAccord2User(string key)
  238. {
  239. string k = GetKeyAccord2User(key);
  240. return PlayerPrefs.HasKey(k);
  241. }
  242. public static string GetKeyAccord2User(string key)
  243. {
  244. return $"{key}@{UID}";
  245. }
  246. public static void SetIntAccord2User(string key, int value)
  247. {
  248. string k = GetKeyAccord2User(key);
  249. PlayerPrefs.DeleteKey(k);
  250. PlayerPrefs.SetInt(k, value);
  251. }
  252. public static int GetIntAccord2User(string key, int value = default(int))
  253. {
  254. return PlayerPrefs.GetInt(GetKeyAccord2User(key), value);
  255. }
  256. public static int GetInt4User(string key)
  257. {
  258. return PlayerPrefs.GetInt(key);
  259. }
  260. public static void SetStringAccord2User(string key, string value)
  261. {
  262. string k = GetKeyAccord2User(key);
  263. PlayerPrefs.DeleteKey(k);
  264. PlayerPrefs.SetString(k, value);
  265. }
  266. public static string GetStringAccord2User(string key, string value = default(string))
  267. {
  268. return PlayerPrefs.GetString(GetKeyAccord2User(key), value);
  269. }
  270. public static void RemoveKeyAccord2User(string key)
  271. {
  272. string k = GetKeyAccord2User(key);
  273. PlayerPrefs.DeleteKey(k);
  274. }
  275. #endregion
  276. /// <summary>
  277. /// 清理内存
  278. /// </summary>
  279. public static void ClearMemory()
  280. {
  281. Resources.UnloadUnusedAssets();
  282. GC.Collect();
  283. }
  284. public static void SetAllChild(Transform trParent, System.Action<Transform> SetChild)
  285. {
  286. Queue<Transform> childList = new Queue<Transform>();
  287. childList.Enqueue(trParent);
  288. while (childList.Count > 0)
  289. {
  290. Transform t = childList.Dequeue();
  291. if (null != SetChild) SetChild(t);
  292. for (int i = 0; i < t.childCount; i++)
  293. {
  294. childList.Enqueue(t.GetChild(i));
  295. }
  296. }
  297. }
  298. public static bool TryParseEnum<T>(string value, out T result)
  299. {
  300. bool isSuccess = false;
  301. try
  302. {
  303. result = (T)Enum.Parse(typeof(T), value);
  304. isSuccess = true;
  305. }
  306. catch
  307. {
  308. result = default(T);
  309. isSuccess = false;
  310. }
  311. return isSuccess;
  312. }
  313. public static bool EnumEquals(Enum m, Enum n)
  314. {
  315. return Equals(m, n);
  316. }
  317. /// <summary>
  318. /// 设置对象层级
  319. /// </summary>
  320. /// <param name="obj"> 目标对象 </param>
  321. /// <param name="layer"> 层级值 </param>
  322. /// <param name="includeChildren"> 是否包含子节点标识,默认为true </param>
  323. public static void SetLayer(GameObject obj, int layer, bool includeChildren = true)
  324. {
  325. if (null == obj)
  326. return;
  327. obj.layer = layer;
  328. if (!includeChildren)
  329. return;
  330. var allTransform = obj.GetComponentsInChildren<Transform>(true);
  331. foreach (Transform trans in allTransform)
  332. {
  333. trans.gameObject.layer = layer;
  334. }
  335. }
  336. /// <summary>
  337. /// 设置对象层级,通过层级名称
  338. /// </summary>
  339. /// <param name="obj"> 目标对象 </param>
  340. /// <param name="layerName"> 层级名称 </param>
  341. /// <param name="includeChildren"> 是否包含子节点标识,默认为true </param>
  342. public static void SetLayerByName(GameObject obj, string layerName, bool includeChildren = true)
  343. {
  344. int layer = LayerMask.NameToLayer(layerName);
  345. SetLayer(obj, layer, includeChildren);
  346. }
  347. private static Random rand;
  348. public static void RandomSeed(int seed)
  349. {
  350. rand = new Random(seed);
  351. }
  352. public static float RandomFloat(float m, float n)
  353. {
  354. if (rand == null)
  355. rand = new Random();
  356. if (n <= m)
  357. return m;
  358. return m + ((float)rand.NextDouble()) * (n - m);
  359. }
  360. public static float RandomInt(int m, int n)
  361. {
  362. if (rand == null)
  363. rand = new Random();
  364. if (n <= m)
  365. return m;
  366. return m + rand.Next() % (m - n);
  367. }
  368. /// <summary>
  369. /// 设置Renderer的渲染层级
  370. /// </summary>
  371. /// <param name="renderer"></param>
  372. /// <param name="sortingLayer"></param>
  373. public static void SetSortingLayer(Renderer renderer, string sortingLayer)
  374. {
  375. renderer.sortingLayerName = sortingLayer;
  376. }
  377. /// <summary>
  378. /// 设置Renderer的渲染顺序
  379. /// </summary>
  380. /// <param name="renderer"></param>
  381. /// <param name="order"></param>
  382. public static void SetSortingOrder(Renderer renderer, int order)
  383. {
  384. renderer.sortingOrder = order;
  385. }
  386. //世界坐标转化为UI坐标
  387. public static Vector2 World2UIPos(Vector3 worldPos, RectTransform uiTrans, Canvas canvas)
  388. {
  389. if (uiTrans == null || canvas == null)
  390. return Vector2.zero;
  391. Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);
  392. screenPos.z = 0;
  393. RectTransformUtility.ScreenPointToLocalPointInRectangle(uiTrans,
  394. screenPos, canvas.worldCamera, out var uiPos);
  395. return uiPos;
  396. }
  397. public static void BinaryWriteInt(BinaryWriter bw, int num)
  398. {
  399. bw.Write(num);
  400. }
  401. public static void BinaryWriteLong(BinaryWriter bw, long num)
  402. {
  403. bw.Write(num);
  404. }
  405. public static void BinaryWriteDouble(BinaryWriter bw, double num)
  406. {
  407. bw.Write(num);
  408. }
  409. public static void BinaryWriteFloat(BinaryWriter bw, float num)
  410. {
  411. bw.Write(num);
  412. }
  413. public static SystemLanguage GetSystemLanguage()
  414. {
  415. return Application.systemLanguage;
  416. }
  417. public static bool CheckStringLegal(string str)
  418. {
  419. if (str == "null" || str == "nil")
  420. return false;
  421. string pattern = @"[@+%+""+'+\s+\n+$+#+\^+\*+]";
  422. var result = Regex.Match(str, pattern);
  423. if (result.Success)
  424. return false;
  425. return true;
  426. }
  427. /// <summary>
  428. /// 使用指定字符串连接多组字符串
  429. /// </summary>
  430. /// <param name="combineStr"> 用于连接的指定字符串 </param>
  431. /// <param name="stringParams"> 连接的内容 </param>
  432. /// <returns></returns>
  433. public static string CombineStrWith(string combineStr, params string[] stringParams)
  434. {
  435. if (stringParams.Length <= 0)
  436. return "";
  437. StringBuilder sb = new StringBuilder();
  438. int count = stringParams.Length;
  439. for (int i = 0; i < count; i++)
  440. {
  441. sb.Append(stringParams[i]);
  442. if (i < count - 1)
  443. sb.Append(combineStr);
  444. }
  445. return sb.ToString();
  446. }
  447. public static string GetFileNameFromPath(string filePath, bool excludeSuffix = false)
  448. {
  449. var name = filePath.Split('/').Last();
  450. if (excludeSuffix)
  451. name = name.Split('.').First();
  452. return name;
  453. }
  454. public static string GenerateLocalDataPath(string fileName, string suffix = ".mp4")
  455. {
  456. string dataPath = "Data/" + fileName + suffix;
  457. return dataPath;
  458. }
  459. public static Vector3 RotateRound(Vector3 position, Vector3 center, Vector3 axis, float angle)
  460. {
  461. Vector3 point = Quaternion.AngleAxis(angle, axis) * (position - center);
  462. Vector3 resultVec3 = center + point;
  463. return resultVec3;
  464. }
  465. /// <summary>
  466. /// 把数据写到本地文件
  467. /// 因为 WriteAllBytes 好像会被代码裁剪掉,在这里实现一下调用
  468. /// </summary>
  469. public static void WriteToLocal(string filePath, byte[] fileBytes, bool cover)
  470. {
  471. if (!cover && File.Exists(filePath))
  472. return;
  473. File.WriteAllBytes(filePath, fileBytes);
  474. }
  475. public static void SetImage(Image image, string path)
  476. {
  477. //var handler = GlobalVariables.ResourceManager.LoadSpriteFromSpriteAtlas(path);
  478. //if (!handler.IsDone)
  479. //{
  480. // Debug.Log(string.Format("Load Sprite %s Error", path));
  481. // return;
  482. //}
  483. //
  484. //image.sprite = handler.Result;
  485. Sprite sprite = Resources.Load<Sprite>(path);
  486. if (!sprite)
  487. {
  488. Debug.LogError("未读取到图片:" + path);
  489. return;
  490. }
  491. image.sprite = sprite;
  492. }
  493. /// <summary>
  494. /// 一个点绕另一个点旋转
  495. /// </summary>
  496. /// <param name="point">要旋转的点</param>
  497. /// <param name="pivot">中心点</param>
  498. /// <param name="euler">旋转的角度</param>
  499. /// <returns></returns>
  500. public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 euler)
  501. {
  502. Vector3 direction = point - pivot;
  503. Vector3 rotatedDirection = Quaternion.Euler(euler) * direction;
  504. Vector3 rotatedPoint = rotatedDirection + pivot;
  505. return rotatedPoint;
  506. }
  507. //设置屏幕常亮状态
  508. public static void SetScreenNeverSleep(bool neverSleep)
  509. {
  510. if (neverSleep)
  511. {
  512. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  513. }
  514. else
  515. {
  516. Screen.sleepTimeout = SleepTimeout.SystemSetting;
  517. }
  518. }
  519. public static Vector2 GetScreenSize(CanvasScaler canvasScaler = null)
  520. {
  521. if (canvasScaler)
  522. {
  523. float realWidth = (Screen.width / ((Screen.height / canvasScaler.referenceResolution.y) * canvasScaler.referenceResolution.x)) * canvasScaler.referenceResolution.x;
  524. float realHeight = canvasScaler.referenceResolution.y;
  525. return new Vector2(realWidth, realHeight);
  526. }
  527. else
  528. {
  529. return new Vector2(Screen.width, Screen.height);
  530. }
  531. }
  532. public static Color List2Color(List<int> list)
  533. {
  534. int a = 255;
  535. if (list.Count > 3)
  536. {
  537. a = list[3];
  538. }
  539. return new Color(list[0] / 255f, list[1] / 255f, list[2] / 255f, a / 255f);
  540. }
  541. //public static async Task WaitUntil(Func<bool> predicate, int sleep = 50)
  542. //{
  543. // while (!predicate())
  544. // {
  545. // await Task.Delay(sleep);
  546. // }
  547. //}
  548. public static async void DelayDoFunc(int delay, UnityAction action)
  549. {
  550. await Task.Delay(delay);
  551. action?.Invoke();
  552. }
  553. public static void ChangeAllLayer(GameObject go, int layer)
  554. {
  555. go.layer = layer;
  556. for (int i = 0; i < go.transform.childCount; i++)
  557. {
  558. ChangeAllLayer(go.transform.GetChild(i).gameObject, layer);
  559. }
  560. }
  561. public static void ShuffleList<T>(List<T> list, int seed = 0)
  562. {
  563. System.Random rng;
  564. if (seed == 0)
  565. {
  566. rng = new System.Random();
  567. }
  568. else
  569. {
  570. rng = new System.Random(seed);
  571. }
  572. int n = list.Count;
  573. while (n > 1)
  574. {
  575. n--;
  576. int k = rng.Next(n + 1);
  577. T value = list[k];
  578. list[k] = list[n];
  579. list[n] = value;
  580. }
  581. }
  582. public static bool CheckCanHit(string selfTag, string otherTag)
  583. {
  584. switch (selfTag)
  585. {
  586. case "Player":
  587. if (otherTag == "Enemy" || otherTag == "EnemyTower")
  588. {
  589. return true;
  590. }
  591. break;
  592. case "Demonic":
  593. if (otherTag == "Enemy" || otherTag == "EnemyTower" || otherTag == "Portal" || otherTag == "Boss")
  594. {
  595. return true;
  596. }
  597. break;
  598. case "Tower":
  599. if (otherTag == "Enemy" || otherTag == "EnemyTower" || otherTag == "Boss")
  600. {
  601. return true;
  602. }
  603. break;
  604. case "Enemy":
  605. if (otherTag == "Player" || otherTag == "Demonic" || otherTag == "Tower")
  606. {
  607. return true;
  608. }
  609. break;
  610. case "EnemyTower":
  611. if (otherTag == "Player" || otherTag == "Demonic" || otherTag == "Tower")
  612. {
  613. return true;
  614. }
  615. break;
  616. case "Boss":
  617. if (otherTag == "Player" || otherTag == "Demonic" || otherTag == "Tower")
  618. {
  619. return true;
  620. }
  621. break;
  622. default:
  623. break;
  624. }
  625. return false;
  626. }
  627. }
  628. }