PrefabDependenciesTask.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using XGame.Framework.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEditor;
  6. namespace XGame.Editor.Asset.Tools
  7. {
  8. public class PrefabDependenciesTask
  9. {
  10. private class PrefabInfo
  11. {
  12. public string assetPath;
  13. public string[] dependencies;
  14. }
  15. private HashSet<string> _prefabPaths;
  16. private List<string> _tempDependencies;
  17. private List<PrefabInfo> _prefabInfos;
  18. public void Run()
  19. {
  20. Init();
  21. FindDependencies();
  22. Export();
  23. }
  24. private void Init()
  25. {
  26. var assetRoots = FileUtil.GetProductAssetsRoots();
  27. var prefabGUIDs = AssetDatabase.FindAssets("t:Prefab", assetRoots);
  28. _prefabPaths = new HashSet<string>();
  29. foreach (var guid in prefabGUIDs)
  30. {
  31. var assetPath = AssetDatabase.GUIDToAssetPath(guid);
  32. _prefabPaths.Add(assetPath);
  33. }
  34. _tempDependencies = new List<string>();
  35. _prefabInfos = new List<PrefabInfo>();
  36. }
  37. private void FindDependencies()
  38. {
  39. var index = 0;
  40. var count = _prefabPaths.Count;
  41. foreach (var assetPath in _prefabPaths)
  42. {
  43. EditorUtility.DisplayProgressBar("检测可加载资源的预制依赖...", $"Path:{assetPath}", (++index) / (float)count);
  44. FindDependencies(assetPath);
  45. }
  46. EditorUtility.ClearProgressBar();
  47. }
  48. private void FindDependencies(string assetPath)
  49. {
  50. // 只检测直接依赖
  51. var deps = AssetDatabase.GetDependencies(assetPath, false);
  52. foreach (var dep in deps)
  53. {
  54. if (dep == assetPath)
  55. {
  56. continue;
  57. }
  58. if (_prefabPaths.Contains(dep))
  59. {
  60. _tempDependencies.Add(dep);
  61. }
  62. }
  63. if (_tempDependencies.Count > 0)
  64. {
  65. _prefabInfos.Add(new PrefabInfo()
  66. {
  67. assetPath = assetPath,
  68. dependencies = _tempDependencies.ToArray()
  69. });
  70. _tempDependencies.Clear();
  71. }
  72. }
  73. private void Export()
  74. {
  75. try
  76. {
  77. if (_prefabInfos.Count == 0)
  78. {
  79. UnityEngine.Debug.Log("PrefabDependencies Completed.");
  80. return;
  81. }
  82. var str = XJson.ToJson(_prefabInfos);
  83. var path = Path.Combine(Path.GetTempPath(), "PrefabDependencies.json");
  84. File.WriteAllText(path, str);
  85. UnityEngine.Debug.Log($"PrefabDependencies 输出路径:{path}");
  86. #if UNITY_EDITOR_WIN
  87. var proc = System.Diagnostics.Process.Start("notepad.exe", path);
  88. #endif
  89. }
  90. catch (Exception e)
  91. {
  92. UnityEngine.Debug.LogException(e);
  93. }
  94. }
  95. }
  96. }