EditorTools.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using System.Linq;
  6. using System.IO;
  7. using System.Text;
  8. using UnityEngine;
  9. using UnityEditor;
  10. using UnityEditor.SceneManagement;
  11. namespace YooAsset.Editor
  12. {
  13. /// <summary>
  14. /// 编辑器工具类
  15. /// </summary>
  16. public static class EditorTools
  17. {
  18. static EditorTools()
  19. {
  20. InitAssembly();
  21. }
  22. #region Assembly
  23. #if UNITY_2019_4_OR_NEWER
  24. private static void InitAssembly()
  25. {
  26. }
  27. /// <summary>
  28. /// 获取带继承关系的所有类的类型
  29. /// </summary>
  30. public static List<Type> GetAssignableTypes(System.Type parentType)
  31. {
  32. TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom(parentType);
  33. return collection.ToList();
  34. }
  35. /// <summary>
  36. /// 获取带有指定属性的所有类的类型
  37. /// </summary>
  38. public static List<Type> GetTypesWithAttribute(System.Type attrType)
  39. {
  40. TypeCache.TypeCollection collection = TypeCache.GetTypesWithAttribute(attrType);
  41. return collection.ToList();
  42. }
  43. #else
  44. private static readonly List<Type> _cacheTypes = new List<Type>(10000);
  45. private static void InitAssembly()
  46. {
  47. _cacheTypes.Clear();
  48. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  49. foreach (Assembly assembly in assemblies)
  50. {
  51. List<Type> types = assembly.GetTypes().ToList();
  52. _cacheTypes.AddRange(types);
  53. }
  54. }
  55. /// <summary>
  56. /// 获取带继承关系的所有类的类型
  57. /// </summary>
  58. public static List<Type> GetAssignableTypes(System.Type parentType)
  59. {
  60. List<Type> result = new List<Type>();
  61. for (int i = 0; i < _cacheTypes.Count; i++)
  62. {
  63. Type type = _cacheTypes[i];
  64. if (parentType.IsAssignableFrom(type))
  65. {
  66. if (type.Name == parentType.Name)
  67. continue;
  68. result.Add(type);
  69. }
  70. }
  71. return result;
  72. }
  73. /// <summary>
  74. /// 获取带有指定属性的所有类的类型
  75. /// </summary>
  76. public static List<Type> GetTypesWithAttribute(System.Type attrType)
  77. {
  78. List<Type> result = new List<Type>();
  79. for (int i = 0; i < _cacheTypes.Count; i++)
  80. {
  81. Type type = _cacheTypes[i];
  82. if (type.GetCustomAttribute(attrType) != null)
  83. {
  84. result.Add(type);
  85. }
  86. }
  87. return result;
  88. }
  89. #endif
  90. /// <summary>
  91. /// 调用私有的静态方法
  92. /// </summary>
  93. /// <param name="type">类的类型</param>
  94. /// <param name="method">类里要调用的方法名</param>
  95. /// <param name="parameters">调用方法传入的参数</param>
  96. public static object InvokeNonPublicStaticMethod(System.Type type, string method, params object[] parameters)
  97. {
  98. var methodInfo = type.GetMethod(method, BindingFlags.NonPublic | BindingFlags.Static);
  99. if (methodInfo == null)
  100. {
  101. UnityEngine.Debug.LogError($"{type.FullName} not found method : {method}");
  102. return null;
  103. }
  104. return methodInfo.Invoke(null, parameters);
  105. }
  106. /// <summary>
  107. /// 调用公开的静态方法
  108. /// </summary>
  109. /// <param name="type">类的类型</param>
  110. /// <param name="method">类里要调用的方法名</param>
  111. /// <param name="parameters">调用方法传入的参数</param>
  112. public static object InvokePublicStaticMethod(System.Type type, string method, params object[] parameters)
  113. {
  114. var methodInfo = type.GetMethod(method, BindingFlags.Public | BindingFlags.Static);
  115. if (methodInfo == null)
  116. {
  117. UnityEngine.Debug.LogError($"{type.FullName} not found method : {method}");
  118. return null;
  119. }
  120. return methodInfo.Invoke(null, parameters);
  121. }
  122. #endregion
  123. #region PackageManager
  124. public static string GetPackageManagerYooVersion()
  125. {
  126. #if UNITY_2019_4_OR_NEWER
  127. UnityEditor.PackageManager.PackageInfo packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(YooAssets).Assembly);
  128. if (packageInfo != null)
  129. return packageInfo.version;
  130. else
  131. return string.Empty;
  132. #else
  133. return string.Empty;
  134. #endif
  135. }
  136. #endregion
  137. #region EditorUtility
  138. /// <summary>
  139. /// 搜集资源
  140. /// </summary>
  141. /// <param name="searchType">搜集的资源类型</param>
  142. /// <param name="searchInFolders">指定搜索的文件夹列表</param>
  143. /// <returns>返回搜集到的资源路径列表</returns>
  144. public static string[] FindAssets(EAssetSearchType searchType, string[] searchInFolders)
  145. {
  146. // 注意:AssetDatabase.FindAssets()不支持末尾带分隔符的文件夹路径
  147. for (int i = 0; i < searchInFolders.Length; i++)
  148. {
  149. string folderPath = searchInFolders[i];
  150. searchInFolders[i] = folderPath.TrimEnd('/');
  151. }
  152. // 注意:获取指定目录下的所有资源对象(包括子文件夹)
  153. string[] guids;
  154. if (searchType == EAssetSearchType.All)
  155. guids = AssetDatabase.FindAssets(string.Empty, searchInFolders);
  156. else
  157. guids = AssetDatabase.FindAssets($"t:{searchType}", searchInFolders);
  158. // 注意:AssetDatabase.FindAssets()可能会获取到重复的资源
  159. HashSet<string> result = new HashSet<string>();
  160. for (int i = 0; i < guids.Length; i++)
  161. {
  162. string guid = guids[i];
  163. string assetPath = AssetDatabase.GUIDToAssetPath(guid);
  164. if (result.Contains(assetPath) == false)
  165. {
  166. result.Add(assetPath);
  167. }
  168. }
  169. // 返回结果
  170. return result.ToArray();
  171. }
  172. /// <summary>
  173. /// 搜集资源
  174. /// </summary>
  175. /// <param name="searchType">搜集的资源类型</param>
  176. /// <param name="searchInFolder">指定搜索的文件夹</param>
  177. /// <returns>返回搜集到的资源路径列表</returns>
  178. public static string[] FindAssets(EAssetSearchType searchType, string searchInFolder)
  179. {
  180. return FindAssets(searchType, new string[] { searchInFolder });
  181. }
  182. /// <summary>
  183. /// 打开搜索面板
  184. /// </summary>
  185. /// <param name="title">标题名称</param>
  186. /// <param name="defaultPath">默认搜索路径</param>
  187. /// <returns>返回选择的文件夹绝对路径,如果无效返回NULL</returns>
  188. public static string OpenFolderPanel(string title, string defaultPath, string defaultName = "")
  189. {
  190. string openPath = EditorUtility.OpenFolderPanel(title, defaultPath, defaultName);
  191. if (string.IsNullOrEmpty(openPath))
  192. return null;
  193. if (openPath.Contains("/Assets") == false)
  194. {
  195. Debug.LogWarning("Please select unity assets folder.");
  196. return null;
  197. }
  198. return openPath;
  199. }
  200. /// <summary>
  201. /// 打开搜索面板
  202. /// </summary>
  203. /// <param name="title">标题名称</param>
  204. /// <param name="defaultPath">默认搜索路径</param>
  205. /// <returns>返回选择的文件绝对路径,如果无效返回NULL</returns>
  206. public static string OpenFilePath(string title, string defaultPath, string extension = "")
  207. {
  208. string openPath = EditorUtility.OpenFilePanel(title, defaultPath, extension);
  209. if (string.IsNullOrEmpty(openPath))
  210. return null;
  211. if (openPath.Contains("/Assets") == false)
  212. {
  213. Debug.LogWarning("Please select unity assets file.");
  214. return null;
  215. }
  216. return openPath;
  217. }
  218. /// <summary>
  219. /// 显示进度框
  220. /// </summary>
  221. public static void DisplayProgressBar(string tips, int progressValue, int totalValue)
  222. {
  223. EditorUtility.DisplayProgressBar("进度", $"{tips} : {progressValue}/{totalValue}", (float)progressValue / totalValue);
  224. }
  225. /// <summary>
  226. /// 隐藏进度框
  227. /// </summary>
  228. public static void ClearProgressBar()
  229. {
  230. EditorUtility.ClearProgressBar();
  231. }
  232. #endregion
  233. #region EditorWindow
  234. public static void FocusUnitySceneWindow()
  235. {
  236. EditorWindow.FocusWindowIfItsOpen<SceneView>();
  237. }
  238. public static void CloseUnityGameWindow()
  239. {
  240. System.Type T = Assembly.Load("UnityEditor").GetType("UnityEditor.GameView");
  241. EditorWindow.GetWindow(T, false, "GameView", true).Close();
  242. }
  243. public static void FocusUnityGameWindow()
  244. {
  245. System.Type T = Assembly.Load("UnityEditor").GetType("UnityEditor.GameView");
  246. EditorWindow.GetWindow(T, false, "GameView", true);
  247. }
  248. public static void FocueUnityProjectWindow()
  249. {
  250. System.Type T = Assembly.Load("UnityEditor").GetType("UnityEditor.ProjectBrowser");
  251. EditorWindow.GetWindow(T, false, "Project", true);
  252. }
  253. public static void FocusUnityHierarchyWindow()
  254. {
  255. System.Type T = Assembly.Load("UnityEditor").GetType("UnityEditor.SceneHierarchyWindow");
  256. EditorWindow.GetWindow(T, false, "Hierarchy", true);
  257. }
  258. public static void FocusUnityInspectorWindow()
  259. {
  260. System.Type T = Assembly.Load("UnityEditor").GetType("UnityEditor.InspectorWindow");
  261. EditorWindow.GetWindow(T, false, "Inspector", true);
  262. }
  263. public static void FocusUnityConsoleWindow()
  264. {
  265. System.Type T = Assembly.Load("UnityEditor").GetType("UnityEditor.ConsoleWindow");
  266. EditorWindow.GetWindow(T, false, "Console", true);
  267. }
  268. #endregion
  269. #region EditorConsole
  270. private static MethodInfo _clearConsoleMethod;
  271. private static MethodInfo ClearConsoleMethod
  272. {
  273. get
  274. {
  275. if (_clearConsoleMethod == null)
  276. {
  277. Assembly assembly = Assembly.GetAssembly(typeof(SceneView));
  278. System.Type logEntries = assembly.GetType("UnityEditor.LogEntries");
  279. _clearConsoleMethod = logEntries.GetMethod("Clear");
  280. }
  281. return _clearConsoleMethod;
  282. }
  283. }
  284. /// <summary>
  285. /// 清空控制台
  286. /// </summary>
  287. public static void ClearUnityConsole()
  288. {
  289. ClearConsoleMethod.Invoke(new object(), null);
  290. }
  291. #endregion
  292. #region SceneUtility
  293. public static bool HasDirtyScenes()
  294. {
  295. var sceneCount = EditorSceneManager.sceneCount;
  296. for (var i = 0; i < sceneCount; ++i)
  297. {
  298. var scene = EditorSceneManager.GetSceneAt(i);
  299. if (scene.isDirty)
  300. return true;
  301. }
  302. return false;
  303. }
  304. #endregion
  305. #region StringUtility
  306. public static string RemoveFirstChar(string str)
  307. {
  308. if (string.IsNullOrEmpty(str))
  309. return str;
  310. return str.Substring(1);
  311. }
  312. public static string RemoveLastChar(string str)
  313. {
  314. if (string.IsNullOrEmpty(str))
  315. return str;
  316. return str.Substring(0, str.Length - 1);
  317. }
  318. public static List<string> StringToStringList(string str, char separator)
  319. {
  320. List<string> result = new List<string>();
  321. if (!String.IsNullOrEmpty(str))
  322. {
  323. string[] splits = str.Split(separator);
  324. foreach (string split in splits)
  325. {
  326. string value = split.Trim(); //移除首尾空格
  327. if (!String.IsNullOrEmpty(value))
  328. {
  329. result.Add(value);
  330. }
  331. }
  332. }
  333. return result;
  334. }
  335. public static T NameToEnum<T>(string name)
  336. {
  337. if (Enum.IsDefined(typeof(T), name) == false)
  338. {
  339. throw new ArgumentException($"Enum {typeof(T)} is not defined name {name}");
  340. }
  341. return (T)Enum.Parse(typeof(T), name);
  342. }
  343. #endregion
  344. #region 文件
  345. /// <summary>
  346. /// 创建文件所在的目录
  347. /// </summary>
  348. /// <param name="filePath">文件路径</param>
  349. public static void CreateFileDirectory(string filePath)
  350. {
  351. string destDirectory = Path.GetDirectoryName(filePath);
  352. CreateDirectory(destDirectory);
  353. }
  354. /// <summary>
  355. /// 创建文件夹
  356. /// </summary>
  357. public static bool CreateDirectory(string directory)
  358. {
  359. if (Directory.Exists(directory) == false)
  360. {
  361. Directory.CreateDirectory(directory);
  362. return true;
  363. }
  364. else
  365. {
  366. return false;
  367. }
  368. }
  369. /// <summary>
  370. /// 删除文件夹及子目录
  371. /// </summary>
  372. public static bool DeleteDirectory(string directory)
  373. {
  374. if (Directory.Exists(directory))
  375. {
  376. Directory.Delete(directory, true);
  377. return true;
  378. }
  379. else
  380. {
  381. return false;
  382. }
  383. }
  384. /// <summary>
  385. /// 文件重命名
  386. /// </summary>
  387. public static void FileRename(string filePath, string newName)
  388. {
  389. string dirPath = Path.GetDirectoryName(filePath);
  390. string destPath;
  391. if (Path.HasExtension(filePath))
  392. {
  393. string extentsion = Path.GetExtension(filePath);
  394. destPath = $"{dirPath}/{newName}{extentsion}";
  395. }
  396. else
  397. {
  398. destPath = $"{dirPath}/{newName}";
  399. }
  400. FileInfo fileInfo = new FileInfo(filePath);
  401. fileInfo.MoveTo(destPath);
  402. }
  403. /// <summary>
  404. /// 移动文件
  405. /// </summary>
  406. public static void MoveFile(string filePath, string destPath)
  407. {
  408. if (File.Exists(destPath))
  409. File.Delete(destPath);
  410. FileInfo fileInfo = new FileInfo(filePath);
  411. fileInfo.MoveTo(destPath);
  412. }
  413. /// <summary>
  414. /// 拷贝文件夹
  415. /// 注意:包括所有子目录的文件
  416. /// </summary>
  417. public static void CopyDirectory(string sourcePath, string destPath)
  418. {
  419. sourcePath = EditorTools.GetRegularPath(sourcePath);
  420. // If the destination directory doesn't exist, create it.
  421. if (Directory.Exists(destPath) == false)
  422. Directory.CreateDirectory(destPath);
  423. string[] fileList = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
  424. foreach (string file in fileList)
  425. {
  426. string temp = EditorTools.GetRegularPath(file);
  427. string savePath = temp.Replace(sourcePath, destPath);
  428. CopyFile(file, savePath, true);
  429. }
  430. }
  431. /// <summary>
  432. /// 拷贝文件
  433. /// </summary>
  434. public static void CopyFile(string sourcePath, string destPath, bool overwrite)
  435. {
  436. if (File.Exists(sourcePath) == false)
  437. throw new FileNotFoundException(sourcePath);
  438. // 创建目录
  439. CreateFileDirectory(destPath);
  440. // 复制文件
  441. File.Copy(sourcePath, destPath, overwrite);
  442. }
  443. /// <summary>
  444. /// 清空文件夹
  445. /// </summary>
  446. /// <param name="folderPath">要清理的文件夹路径</param>
  447. public static void ClearFolder(string directoryPath)
  448. {
  449. if (Directory.Exists(directoryPath) == false)
  450. return;
  451. // 删除文件
  452. string[] allFiles = Directory.GetFiles(directoryPath);
  453. for (int i = 0; i < allFiles.Length; i++)
  454. {
  455. File.Delete(allFiles[i]);
  456. }
  457. // 删除文件夹
  458. string[] allFolders = Directory.GetDirectories(directoryPath);
  459. for (int i = 0; i < allFolders.Length; i++)
  460. {
  461. Directory.Delete(allFolders[i], true);
  462. }
  463. }
  464. /// <summary>
  465. /// 获取文件字节大小
  466. /// </summary>
  467. public static long GetFileSize(string filePath)
  468. {
  469. FileInfo fileInfo = new FileInfo(filePath);
  470. return fileInfo.Length;
  471. }
  472. /// <summary>
  473. /// 读取文件的所有文本内容
  474. /// </summary>
  475. public static string ReadFileAllText(string filePath)
  476. {
  477. if (File.Exists(filePath) == false)
  478. return string.Empty;
  479. return File.ReadAllText(filePath, Encoding.UTF8);
  480. }
  481. /// <summary>
  482. /// 读取文本的所有文本内容
  483. /// </summary>
  484. public static string[] ReadFileAllLine(string filePath)
  485. {
  486. if (File.Exists(filePath) == false)
  487. return null;
  488. return File.ReadAllLines(filePath, Encoding.UTF8);
  489. }
  490. /// <summary>
  491. /// 检测AssetBundle文件是否合法
  492. /// </summary>
  493. public static bool CheckBundleFileValid(byte[] fileData)
  494. {
  495. string signature = ReadStringToNull(fileData, 20);
  496. if (signature == "UnityFS" || signature == "UnityRaw" || signature == "UnityWeb" || signature == "\xFA\xFA\xFA\xFA\xFA\xFA\xFA\xFA")
  497. return true;
  498. else
  499. return false;
  500. }
  501. private static string ReadStringToNull(byte[] data, int maxLength)
  502. {
  503. List<byte> bytes = new List<byte>();
  504. for (int i = 0; i < data.Length; i++)
  505. {
  506. if (i >= maxLength)
  507. break;
  508. byte bt = data[i];
  509. if (bt == 0)
  510. break;
  511. bytes.Add(bt);
  512. }
  513. if (bytes.Count == 0)
  514. return string.Empty;
  515. else
  516. return Encoding.UTF8.GetString(bytes.ToArray());
  517. }
  518. #endregion
  519. #region 路径
  520. /// <summary>
  521. /// 获取规范的路径
  522. /// </summary>
  523. public static string GetRegularPath(string path)
  524. {
  525. return path.Replace('\\', '/').Replace("\\", "/"); //替换为Linux路径格式
  526. }
  527. /// <summary>
  528. /// 移除路径里的后缀名
  529. /// </summary>
  530. public static string RemoveExtension(string str)
  531. {
  532. if (string.IsNullOrEmpty(str))
  533. return str;
  534. int index = str.LastIndexOf('.');
  535. if (index == -1)
  536. return str;
  537. else
  538. return str.Remove(index); //"assets/config/test.unity3d" --> "assets/config/test"
  539. }
  540. /// <summary>
  541. /// 获取项目工程路径
  542. /// </summary>
  543. public static string GetProjectPath()
  544. {
  545. string projectPath = Path.GetDirectoryName(Application.dataPath);
  546. return GetRegularPath(projectPath);
  547. }
  548. /// <summary>
  549. /// 转换文件的绝对路径为Unity资源路径
  550. /// 例如 D:\\YourPorject\\Assets\\Works\\file.txt 替换为 Assets/Works/file.txt
  551. /// </summary>
  552. public static string AbsolutePathToAssetPath(string absolutePath)
  553. {
  554. string content = GetRegularPath(absolutePath);
  555. return Substring(content, "Assets/", true);
  556. }
  557. /// <summary>
  558. /// 转换Unity资源路径为文件的绝对路径
  559. /// 例如:Assets/Works/file.txt 替换为 D:\\YourPorject/Assets/Works/file.txt
  560. /// </summary>
  561. public static string AssetPathToAbsolutePath(string assetPath)
  562. {
  563. string projectPath = GetProjectPath();
  564. return $"{projectPath}/{assetPath}";
  565. }
  566. /// <summary>
  567. /// 递归查找目标文件夹路径
  568. /// </summary>
  569. /// <param name="root">搜索的根目录</param>
  570. /// <param name="folderName">目标文件夹名称</param>
  571. /// <returns>返回找到的文件夹路径,如果没有找到返回空字符串</returns>
  572. public static string FindFolder(string root, string folderName)
  573. {
  574. DirectoryInfo rootInfo = new DirectoryInfo(root);
  575. DirectoryInfo[] infoList = rootInfo.GetDirectories();
  576. for (int i = 0; i < infoList.Length; i++)
  577. {
  578. string fullPath = infoList[i].FullName;
  579. if (infoList[i].Name == folderName)
  580. return fullPath;
  581. string result = FindFolder(fullPath, folderName);
  582. if (string.IsNullOrEmpty(result) == false)
  583. return result;
  584. }
  585. return string.Empty;
  586. }
  587. /// <summary>
  588. /// 截取字符串
  589. /// 获取匹配到的后面内容
  590. /// </summary>
  591. /// <param name="content">内容</param>
  592. /// <param name="key">关键字</param>
  593. /// <param name="includeKey">分割的结果里是否包含关键字</param>
  594. /// <param name="searchBegin">是否使用初始匹配的位置,否则使用末尾匹配的位置</param>
  595. public static string Substring(string content, string key, bool includeKey, bool firstMatch = true)
  596. {
  597. if (string.IsNullOrEmpty(key))
  598. return content;
  599. int startIndex = -1;
  600. if (firstMatch)
  601. startIndex = content.IndexOf(key); //返回子字符串第一次出现位置
  602. else
  603. startIndex = content.LastIndexOf(key); //返回子字符串最后出现的位置
  604. // 如果没有找到匹配的关键字
  605. if (startIndex == -1)
  606. return content;
  607. if (includeKey)
  608. return content.Substring(startIndex);
  609. else
  610. return content.Substring(startIndex + key.Length);
  611. }
  612. #endregion
  613. }
  614. }