EditorTools.cs 16 KB

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