UnityUtil.cs 31 KB

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