UnityUtil.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Text;
  5. #if UNITY_EDITOR
  6. using UnityEditor;
  7. #endif
  8. using UnityEngine;
  9. using UnityEngine.Networking;
  10. using UnityEngine.Video;
  11. namespace XRTool.Util
  12. {
  13. /// <summary>
  14. /// 工具类,各种常用算法的集合脚本
  15. /// </summary>
  16. public static class UnityUtil
  17. {
  18. public const int MB = 1024 * 1024;
  19. public const long GB = 1024 * 1024 * 1024;
  20. public const string MBString = "MB";
  21. public const string GBString = "GB";
  22. /// <summary>
  23. /// 全局唯一id
  24. /// 自动自增
  25. /// </summary>
  26. private static int unicode = 10000000;
  27. #if UNITY_EDITOR
  28. /// <summary>
  29. /// 尝试得到一个未命名的名称
  30. /// 下标从0开始检索,如果不存在此名字的文字,则返回此名字
  31. /// 如果存在,下标++
  32. /// </summary>
  33. /// <typeparam name="T"></typeparam>
  34. /// <param name="path"></param>
  35. /// <param name="suffix"></param>
  36. /// <returns></returns>
  37. public static string TryGetName<T>(string path, string suffix = ".asset")
  38. {
  39. int index = 0;
  40. string confName = "";
  41. UnityEngine.Object obj = null;
  42. do
  43. {
  44. confName = path + "/" + typeof(T).Name + "_" + index + suffix;
  45. obj = AssetDatabase.LoadAssetAtPath(confName, typeof(T));
  46. index++;
  47. } while (obj);
  48. return confName;
  49. }
  50. public static string TryGetName(Type T, string path, string suffix = ".asset")
  51. {
  52. int index = 0;
  53. string confName = "";
  54. UnityEngine.Object obj = null;
  55. do
  56. {
  57. confName = path + "/" + T.Name + "_" + index + suffix;
  58. obj = AssetDatabase.LoadAssetAtPath(confName, T);
  59. index++;
  60. } while (obj);
  61. return confName;
  62. }
  63. #endif
  64. /// <summary>
  65. /// 获取指定名称类型的对象
  66. /// </summary>
  67. /// <typeparam name="T"></typeparam>
  68. /// <param name="childName"></param>
  69. /// <returns></returns>
  70. public static T GetChild<T>(Transform target, string childName)
  71. {
  72. var child = target.Find(childName);
  73. if (child)
  74. {
  75. return child.GetComponent<T>();
  76. }
  77. return default(T);
  78. }
  79. /// <summary>
  80. /// 深度优先搜索查找子物体
  81. /// </summary>
  82. /// <typeparam name="T"></typeparam>
  83. /// <param name="childName"></param>
  84. /// <returns></returns>
  85. public static T GetDepthChild<T>(Transform transform, string childName)
  86. {
  87. Transform target = FindDepthTransf(transform, childName);
  88. if (target)
  89. return GetT<T>(target.gameObject);
  90. return default(T);
  91. }
  92. public static GameObject GetDepthChild(Transform transform, string childName)
  93. {
  94. Transform target = FindDepthTransf(transform, childName);
  95. if (target)
  96. return target.gameObject;
  97. return null;
  98. }
  99. /// <summary>
  100. /// 广度优先查找子物体
  101. /// </summary>
  102. /// <typeparam name="T"></typeparam>
  103. /// <param name="childName"></param>
  104. /// <returns></returns>
  105. public static T GetBreadthChild<T>(Transform transform, string childName)
  106. {
  107. Transform target = FindBreadthTransf(transform, childName);
  108. if (target)
  109. return GetT<T>(target.gameObject);
  110. return default(T);
  111. }
  112. public static GameObject GetBreadthChild(Transform transform, string childName)
  113. {
  114. Transform target = FindBreadthTransf(transform, childName);
  115. if (target)
  116. return target.gameObject;
  117. return null;
  118. }
  119. public static T GetParent<T>(Transform transform)
  120. {
  121. return transform.GetComponentInParent<T>();
  122. }
  123. public static T GetChild<T>(Transform trans)
  124. {
  125. return trans.GetComponentInChildren<T>();
  126. }
  127. public static T GetT<T>(GameObject target)
  128. {
  129. return target.GetComponent<T>();
  130. }
  131. /// <summary>
  132. /// 深度优先检索子物体
  133. /// </summary>
  134. /// <param name="check"></param>
  135. /// <param name="childName"></param>
  136. /// <returns></returns>
  137. public static Transform FindDepthTransf(Transform check, string childName)
  138. {
  139. if (check.name == childName) return check;
  140. for (int i = 0; i < check.childCount; i++)
  141. {
  142. Transform obj = FindDepthTransf(check.GetChild(i), childName);
  143. if (obj)
  144. return obj;
  145. }
  146. return null;
  147. }
  148. /// <summary>
  149. /// 广度优先检索子物体
  150. /// </summary>
  151. /// <param name="check"></param>
  152. /// <param name="childName"></param>
  153. /// <returns></returns>
  154. public static Transform FindBreadthTransf(Transform check, string childName)
  155. {
  156. Transform forreturn = check.Find(childName);
  157. if (forreturn)
  158. {
  159. return forreturn;
  160. }
  161. if (check.childCount > 0)
  162. {
  163. for (int i = 0; i < check.childCount; i++)
  164. {
  165. var target = FindBreadthTransf(check.GetChild(i), childName);
  166. if (target)
  167. {
  168. return target;
  169. }
  170. }
  171. }
  172. return forreturn;
  173. }
  174. public static void SetParent(Transform parent, Transform child)
  175. {
  176. child.SetParent(parent);
  177. child.localPosition = Vector3.zero;
  178. child.localRotation = Quaternion.identity;
  179. child.localScale = Vector3.one;
  180. }
  181. /// <summary>
  182.         /// 去除文件bom头后的字符
  183.         /// </summary>
  184.         /// <param name="buffer"></param>
  185.         /// <returns></returns>
  186. public static string GetUTF8String(byte[] buffer)
  187. {
  188. if (buffer == null)
  189. return null;
  190. if (buffer.Length <= 3)
  191. {
  192. return Encoding.UTF8.GetString(buffer);
  193. }
  194. byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
  195. if (buffer[0] == bomBuffer[0]
  196. && buffer[1] == bomBuffer[1]
  197. && buffer[2] == bomBuffer[2])
  198. {
  199. return new UTF8Encoding(false).GetString(buffer, 3, buffer.Length - 3);
  200. }
  201. return Encoding.UTF8.GetString(buffer);
  202. }
  203. /// <summary>
  204. /// 获取距离放歌最近的数字
  205. /// 四舍五入
  206. /// </summary>
  207. /// <param name="num"></param>
  208. /// <param name="cell"></param>
  209. /// <returns></returns>
  210. public static float GetNearst(float num, float cell)
  211. {
  212. int dir = num < 0 ? -1 : 1;
  213. return ((int)(num + cell / 2 * dir) / (int)cell) * cell;
  214. }
  215. /// <summary>
  216. /// 判断两个矩形是否相交
  217. /// 如果两个矩形中心点在x、y轴的投影距离分别小于矩形的边长之和,则此矩形相交
  218. /// </summary>
  219. /// <param name="a"></param>
  220. /// <param name="b"></param>
  221. /// <returns></returns>
  222. public static bool IsCrossLine(Rect a, Rect b)
  223. {
  224. Vector2 dis = b.center - a.center;
  225. if (((int)a.width + (int)b.width) / 2 > Math.Abs(dis.x) && ((int)a.height + (int)b.height) / 2 > Math.Abs(dis.y))
  226. {
  227. return true;
  228. }
  229. return false;
  230. }
  231. public static void ChangeMateColor(Renderer render, Color color, string name = "_Color")
  232. {
  233. if (render)
  234. {
  235. MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
  236. render.GetPropertyBlock(propertyBlock);
  237. propertyBlock.SetColor(name, color);
  238. render.SetPropertyBlock(propertyBlock);
  239. //ChangeMateValue(render, propertyBlock);
  240. propertyBlock = null;
  241. }
  242. }
  243. public static void ChangeMateColor(MaterialPropertyBlock propertyBlock, Renderer render, Color color, string name = "_Color")
  244. {
  245. if (render)
  246. {
  247. render.GetPropertyBlock(propertyBlock);
  248. propertyBlock.SetColor(name, color);
  249. render.SetPropertyBlock(propertyBlock);
  250. //ChangeMateValue(render, propertyBlock);
  251. //propertyBlock = null;
  252. }
  253. }
  254. public static void ChangeMateTexture2D(Renderer render, Texture2D img, string name = "_MainTex")
  255. {
  256. if (render)
  257. {
  258. MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
  259. render.GetPropertyBlock(propertyBlock);
  260. propertyBlock.SetTexture(name, img);
  261. render.SetPropertyBlock(propertyBlock);
  262. propertyBlock = null;
  263. }
  264. }
  265. public static void ChangeMateVideo(GameObject obj, VideoClip video, string name = "_MainTex")
  266. {
  267. if (obj)
  268. {
  269. VideoPlayer vp = obj.GetComponent<VideoPlayer>();
  270. vp.clip = video;
  271. }
  272. }
  273. public static void ChangeMateTexture(Renderer render, Texture img, string name = "_MainTex")
  274. {
  275. if (render)
  276. {
  277. MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
  278. render.GetPropertyBlock(propertyBlock);
  279. propertyBlock.SetTexture(name, img);
  280. render.SetPropertyBlock(propertyBlock);
  281. propertyBlock = null;
  282. }
  283. }
  284. public static void ChangeMateValue(Renderer render, float att, string name = "_Smoothness")
  285. {
  286. if (render)
  287. {
  288. MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
  289. render.GetPropertyBlock(propertyBlock);
  290. propertyBlock.SetFloat(name, att);
  291. render.SetPropertyBlock(propertyBlock);
  292. //ChangeMateValue(render, propertyBlock);
  293. propertyBlock = null;
  294. }
  295. }
  296. public static void ChangeMateValue(Renderer render, Vector4 att, string name = "_Smoothness")
  297. {
  298. if (render)
  299. {
  300. MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
  301. render.GetPropertyBlock(propertyBlock);
  302. propertyBlock.SetVector(name, att);
  303. render.SetPropertyBlock(propertyBlock);
  304. //ChangeMateValue(render, propertyBlock);
  305. propertyBlock = null;
  306. }
  307. }
  308. public static void ChangeMateValue(Renderer render, MaterialPropertyBlock propertyBlock)
  309. {
  310. if (render)
  311. {
  312. //MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
  313. render.GetPropertyBlock(propertyBlock);
  314. //propertyBlock.SetVector(name, att);
  315. render.SetPropertyBlock(propertyBlock);
  316. }
  317. }
  318. /// <summary>
  319. /// 材质复制
  320. /// </summary>
  321. /// <param name="resMate"></param>
  322. /// <param name="targetMate"></param>
  323. public static void CopyMate(Material resMate, Material targetMate)
  324. {
  325. if (resMate && resMate != targetMate)
  326. {
  327. resMate.shader = targetMate.shader;
  328. resMate.CopyPropertiesFromMaterial(targetMate);
  329. }
  330. }
  331. ///// <summary>
  332. /////
  333. ///// </summary>
  334. ///// <returns></returns>
  335. //public static string ArtTransferInfo(ArtInfo info)
  336. //{
  337. // Vector3 pos = GameSession.Instance.GetHeadForwadPos(info.Distance);
  338. // if (GameNode.Instance)
  339. // {
  340. // pos = GameNode.Instance.transform.InverseTransformPoint(pos);
  341. // }
  342. // var angle = Vector3.zero;
  343. // var scale = Vector3.one * info.Size;
  344. // return TransferToString(pos, angle, scale, 2);
  345. //}
  346. public static string TransferToString(Transform tranfer, int state)
  347. {
  348. return TransferToString(tranfer.localPosition, tranfer.localEulerAngles, tranfer.localScale, state);
  349. }
  350. public static int maxTransfer = 1000;
  351. public static string TransferToString(Vector3 pos, Vector3 ang, Vector3 sca, int state)
  352. {
  353. string info = "";
  354. pos *= maxTransfer;
  355. ang *= maxTransfer;
  356. sca *= maxTransfer;
  357. string position = (int)(pos.x) + "," + (int)(pos.y) + "," + (int)(pos.z);
  358. string angle = (int)(ang.x) + "," + (int)(ang.y) + "," + (int)(ang.z);
  359. string scale = (int)(sca.x) + "," + (int)(sca.y) + "," + (int)(sca.z);
  360. info = position + "|" + angle + "|" + scale;
  361. //if (state == 2)
  362. //{
  363. // info = pos + "|" + angle + "|" + scale;
  364. //}
  365. //else if (state == 1)
  366. //{
  367. // info = pos + "|" + angle;
  368. //}
  369. //else if (state == 1)
  370. //{
  371. // info = pos;
  372. //}
  373. return info;
  374. }
  375. //public static Posture GetPosture(Transform info)
  376. //{
  377. // Posture posture = new Posture();
  378. // posture.position = info.localPosition;
  379. // posture.angle = info.localEulerAngles;
  380. // posture.scale = info.localScale;
  381. // posture.count = 2;
  382. // return posture;
  383. //}
  384. //public static void SetPosture(Transform info, Posture posture, float time = -1)
  385. //{
  386. // if (time <= 0)
  387. // {
  388. // info.localPosition = posture.position;
  389. // info.localEulerAngles = posture.angle;
  390. // info.localScale = posture.scale;
  391. // }
  392. // else
  393. // {
  394. // info.DOKill();
  395. // if (posture.count >= 0)
  396. // {
  397. // info.DOLocalMove(posture.position, time);
  398. // }
  399. // if (posture.count >= 1)
  400. // {
  401. // info.DOLocalRotate(posture.angle, time);
  402. // }
  403. // if (posture.count >= 2)
  404. // {
  405. // info.DOScale(posture.scale, time);
  406. // }
  407. // }
  408. //}
  409. //public static Posture GetPosture(string info)
  410. //{
  411. // Posture posture = new Posture();
  412. // string[] arr = info.Split('|');
  413. // for (int i = 0; i < arr.Length; i++)
  414. // {
  415. // if (string.IsNullOrEmpty(arr[i]))
  416. // {
  417. // continue;
  418. // }
  419. // string[] v = arr[i].Split(',');
  420. // Vector3 vector = Vector3.zero;
  421. // vector.x = float.Parse(v[0]);
  422. // vector.y = float.Parse(v[1]);
  423. // vector.z = float.Parse(v[2]);
  424. // //for (int j = 0; j < v.Length; j++)
  425. // //{
  426. // // float value = float.Parse(v[j]);
  427. // // if (j == 0)
  428. // // {
  429. // // vector.x = value;
  430. // // }
  431. // // else if (j == 1)
  432. // // {
  433. // // vector.y = value;
  434. // // }
  435. // // else if (j == 2)
  436. // // {
  437. // // vector.z = value;
  438. // // }
  439. // //}
  440. // vector /= maxTransfer;
  441. // if (i == 0)
  442. // {
  443. // posture.position = vector;
  444. // }
  445. // else if (i == 1)
  446. // {
  447. // posture.angle = vector;
  448. // }
  449. // else if (i == 2)
  450. // {
  451. // posture.scale = vector;
  452. // }
  453. // posture.count = i;
  454. // }
  455. // return posture;
  456. //}
  457. //public static Posture GetPosture(string info)
  458. //{
  459. // Posture posture = new Posture();
  460. // string[] arr = info.Split('|');
  461. // for (int i = 0; i < arr.Length; i++)
  462. // {
  463. // if (string.IsNullOrEmpty(arr[i]))
  464. // {
  465. // continue;
  466. // }
  467. // string[] v = arr[i].Split(',');
  468. // Vector3 vector = Vector3.zero;
  469. // for (int j = 0; j < v.Length; j++)
  470. // {
  471. // float value = float.Parse(v[j]);
  472. // if (j == 0)
  473. // {
  474. // vector.x = value;
  475. // }
  476. // else if (j == 1)
  477. // {
  478. // vector.y = value;
  479. // }
  480. // else if (j == 2)
  481. // {
  482. // vector.z = value;
  483. // }
  484. // }
  485. // vector *= maxTransfer;
  486. // if (i == 0)
  487. // {
  488. // posture.position = vector;
  489. // }
  490. // else if (i == 1)
  491. // {
  492. // posture.angle = vector;
  493. // }
  494. // else if (i == 2)
  495. // {
  496. // posture.scale = vector;
  497. // }
  498. // posture.count = i;
  499. // }
  500. // return posture;
  501. //}
  502. public static Vector3 StringToVector3(string v)
  503. {
  504. Vector3 z = Vector3.zero;
  505. v = v.Replace("(", "").Replace(")", "");
  506. string[] s = v.Split(',');
  507. if (s.Length > 2)
  508. {
  509. z.x = float.Parse(s[0]);
  510. z.y = float.Parse(s[1]);
  511. z.z = float.Parse(s[2]);
  512. z /= maxTransfer;
  513. }
  514. return z;
  515. }
  516. public static string Vector3ToString(Vector3 v)
  517. {
  518. return v.ToString();
  519. }
  520. public static string QuaterToString(Quaternion q)
  521. {
  522. q.x *= maxTransfer;
  523. q.y *= maxTransfer;
  524. q.z *= maxTransfer;
  525. q.w *= maxTransfer;
  526. return q.ToString();
  527. }
  528. public static Quaternion StringToQuater(string v)
  529. {
  530. Quaternion q = Quaternion.identity;
  531. v = v.Replace("(", "").Replace(")", "");
  532. string[] s = v.Split(',');
  533. if (s.Length > 3)
  534. {
  535. q.x = float.Parse(s[0]) / maxTransfer;
  536. q.y = float.Parse(s[1]) / maxTransfer;
  537. q.z = float.Parse(s[2]) / maxTransfer;
  538. q.w = float.Parse(s[3]) / maxTransfer;
  539. }
  540. return q;
  541. }
  542. public static Vector3 RealForward(Transform body)
  543. {
  544. Vector3 right = body.right;
  545. right.y = 0;
  546. return Vector3.Cross(right, Vector3.up);
  547. }
  548. public static string CurTimeString
  549. {
  550. get { return DateTime.Now.ToString("MMddHHmmssf"); }
  551. }
  552. /// <summary>
  553. /// 通过时间生成一个绝对的唯一的id
  554. /// 此id的生成有可能存在重复,如果存在同时的调用方式时
  555. /// </summary>
  556. public static string TimeID
  557. {
  558. get { return DateTime.Now.ToString("HHmmssfffff"); }
  559. }
  560. /// <summary>
  561. /// 全局唯一id
  562. /// </summary>
  563. public static int Unicode
  564. {
  565. get
  566. {
  567. return ++unicode;
  568. }
  569. }
  570. /// <summary>
  571. /// 从URl下载指定的资源
  572. /// </summary>
  573. /// <param name="url">资源的地址,可以是网络路径,也可以是本地文件路径</param>
  574. /// <param name="updateProcess">下载的进度,当前已下载文件大小,以及进度</param>
  575. /// <param name="complete"></param>
  576. /// <param name="form">请求的参数,如果为空代表Get请求,不为空代表Post请求</param>
  577. /// <returns></returns>
  578. public static IEnumerator RequestDownData(string url, Action<string, UnityWebRequest> complete, DownloadHandler hander = null, Action<float, float> updateProcess = null, WWWForm form = null)
  579. {
  580. UnityWebRequest web;
  581. Debug.Log("RequestDownData" + url);
  582. if (form == null)
  583. {
  584. web = UnityWebRequest.Get(url);
  585. }
  586. else
  587. {
  588. web = UnityWebRequest.Post(url, form);
  589. }
  590. if (hander != null)
  591. {
  592. web.downloadHandler = hander;
  593. }
  594. web.SendWebRequest();
  595. while (!web.isDone)
  596. {
  597. updateProcess?.Invoke(web.downloadedBytes, web.downloadProgress);
  598. yield return 0;
  599. }
  600. if (web.isDone)
  601. {
  602. updateProcess?.Invoke(web.downloadedBytes, 1);
  603. }
  604. if (web.isNetworkError || web.isHttpError)
  605. {
  606. complete?.Invoke(web.error, web);
  607. Debug.LogError(web.error + url);
  608. }
  609. else
  610. {
  611. complete?.Invoke(null, web);
  612. }
  613. web.Dispose();
  614. }
  615. /// <summary>
  616. /// 拷贝文件
  617. /// </summary>
  618. /// <param name="SourcePath"></param>
  619. /// <param name="DestinationPath"></param>
  620. /// <param name="overwriteexisting">是否覆盖</param>
  621. /// <returns></returns>
  622. public static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
  623. {
  624. bool ret = false;
  625. try
  626. {
  627. SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
  628. DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
  629. if (Directory.Exists(SourcePath))
  630. {
  631. if (Directory.Exists(DestinationPath) == false)
  632. Directory.CreateDirectory(DestinationPath);
  633. foreach (string fls in Directory.GetFiles(SourcePath))
  634. {
  635. FileInfo flinfo = new FileInfo(fls);
  636. flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
  637. UnityEngine.Debug.Log(flinfo.CreationTime.ToString());
  638. }
  639. foreach (string drs in Directory.GetDirectories(SourcePath))
  640. {
  641. DirectoryInfo drinfo = new DirectoryInfo(drs);
  642. if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
  643. ret = false;
  644. }
  645. }
  646. ret = true;
  647. }
  648. catch (Exception ex)
  649. {
  650. ret = false;
  651. UnityLog.LogError(ex.ToString());
  652. }
  653. return ret;
  654. }
  655. /// <summary>
  656. /// 广度优先,遍历文件
  657. /// </summary>
  658. /// <param name="path"></param>
  659. /// <param name="callBack"></param>
  660. public static void FindFileBreadth(string path, Action<string> callBack)
  661. {
  662. try
  663. {
  664. DirectoryInfo di = new DirectoryInfo(path);
  665. FileInfo[] fis = di.GetFiles();
  666. for (int i = 0; i < fis.Length; i++)
  667. {
  668. callBack?.Invoke(fis[i].FullName);
  669. }
  670. DirectoryInfo[] dis = di.GetDirectories();
  671. for (int j = 0; j < dis.Length; j++)
  672. {
  673. FindFileBreadth(dis[j].FullName, callBack);
  674. }
  675. }
  676. catch (Exception ex)
  677. {
  678. UnityLog.LogError(ex.ToString());
  679. }
  680. }
  681. /// <summary>
  682. /// 深度优先,遍历文件
  683. /// </summary>
  684. /// <param name="dir"></param>
  685. public static void FindFileByDepth(string dir, Action<string> callBack)
  686. {
  687. try
  688. {
  689. DirectoryInfo d = new DirectoryInfo(dir);
  690. FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
  691. foreach (FileSystemInfo fsinfo in fsinfos)
  692. {
  693. if (fsinfo is DirectoryInfo)
  694. {
  695. FindFileByDepth(fsinfo.FullName, callBack);
  696. }
  697. else
  698. {
  699. callBack?.Invoke(fsinfo.FullName);
  700. }
  701. }
  702. }
  703. catch (Exception ex)
  704. {
  705. UnityLog.LogError(ex.ToString());
  706. }
  707. }
  708. /// <summary>
  709. /// 获取文件MD5值
  710. /// </summary>
  711. /// <param name="fileName">文件绝对路径</param>
  712. /// <returns>MD5值</returns>
  713. public static string GetMD5HashFromFile(string fileName)
  714. {
  715. try
  716. {
  717. FileStream file = new FileStream(fileName, FileMode.Open);
  718. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  719. byte[] retVal = md5.ComputeHash(file);
  720. file.Close();
  721. StringBuilder sb = new StringBuilder();
  722. for (int i = 0; i < retVal.Length; i++)
  723. {
  724. sb.Append(retVal[i].ToString("x2"));
  725. }
  726. return sb.ToString();
  727. }
  728. catch (Exception ex)
  729. {
  730. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  731. }
  732. }
  733. /// <summary>
  734. /// 重命名文件
  735. /// </summary>
  736. /// <param name="file"></param>
  737. /// <param name="newFile"></param>
  738. public static void ReNameFile(string file, string newFile)
  739. {
  740. if (File.Exists(file))
  741. {
  742. try
  743. {
  744. string dir = Path.GetDirectoryName(newFile);
  745. if (!Directory.Exists(dir))
  746. {
  747. Directory.CreateDirectory(dir);
  748. }
  749. if (File.Exists(newFile))
  750. {
  751. File.Delete(newFile);
  752. }
  753. FileInfo info = new FileInfo(file);
  754. info.MoveTo(newFile);
  755. }
  756. catch (Exception ex)
  757. {
  758. UnityLog.LogError(file + " is error" + ex.ToString());
  759. }
  760. }
  761. }
  762. /// <summary>
  763. /// 删除文件
  764. /// </summary>
  765. /// <param name="file"></param>
  766. /// <param name="newFile"></param>
  767. public static void DelFile(string file)
  768. {
  769. UnityLog.Log(file + " is Del", 3);
  770. if (File.Exists(file))
  771. {
  772. try
  773. {
  774. File.Delete(file);
  775. }
  776. catch (Exception ex)
  777. {
  778. UnityLog.LogError(file + " is error" + ex.ToString());
  779. }
  780. }
  781. }
  782. public static string ByteToMB(long bytes, int count = 2)
  783. {
  784. return TransNUM(bytes, MB, MBString, count);
  785. }
  786. public static string ByteToGB(long bytes, int count = 2)
  787. {
  788. return TransNUM(bytes, GB, GBString, count);
  789. }
  790. public static string TransNUM(long bytes, long jinzhi, string houzui = "", int count = 2)
  791. {
  792. float num = bytes * 1f / jinzhi;
  793. return num.ToString("f" + count) + houzui;
  794. }
  795. public static Sprite CreateSpriteByData(byte[] data)
  796. {
  797. Texture2D tex = new Texture2D(64, 64);
  798. tex.LoadImage(data);
  799. return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
  800. }
  801. /// <summary>
  802. /// 获取url对应的本地路径
  803. /// </summary>
  804. /// <param name="url"></param>
  805. /// <returns></returns>
  806. public static string GetFilePath(string url, int count = 2)
  807. {
  808. string[] arr = url.Split('/');
  809. string path = url;
  810. if (arr.Length > count)
  811. {
  812. path = "";
  813. for (int i = arr.Length - count; i < arr.Length; i++)
  814. {
  815. if (i != arr.Length - 1)
  816. {
  817. path += arr[i] + "/";
  818. }
  819. else
  820. {
  821. path += arr[i];
  822. }
  823. }
  824. }
  825. return path;
  826. }
  827. }
  828. }