UnityUtil.cs 37 KB

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