Unity 查找资源引用

偏执的太偏执、 2022-12-23 00:58 293阅读 0赞

有时会有这样的需求,在项目中查找某个资源被其他哪些资源引用了。

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTM2NTQxMjU_size_16_color_FFFFFF_t_70

现在Unity中只有查找当前场景的引用,没有查找项目中所有的引用的功能

所以我们自己可以利用一些API:

通过AssetDatabase.GetAllAssetPaths()获取项目中所有的资源路径。
通过AssetDatabase.GetDependencies()获取每一个资源所依赖资源的信息。

完成我们需要的功能。

首先,在Asset文件夹下,新建Editor文件夹,再在Edtior文件夹中新建ReferenceFinder.cs。

  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Threading;
  4. using UnityEditor;
  5. using UnityEngine;
  6. public static class ReferenceFinder
  7. {
  8. static string[] assetGUIDs;
  9. static string[] assetPaths;
  10. static string[] allAssetPaths;
  11. static Thread thread;
  12. [MenuItem("Assets/Find References In Project", false)]
  13. [MenuItem("Assets/Find References In Project", false, 25)]
  14. static void FindreAssetFerencesMenu()
  15. {
  16. Debug.LogError("查找资源引用");
  17. if (Selection.assetGUIDs.Length == 0)
  18. {
  19. Debug.LogError("请先选择任意一个组件,再右键点击此菜单");
  20. return;
  21. }
  22. assetGUIDs = Selection.assetGUIDs;
  23. assetPaths = new string[assetGUIDs.Length];
  24. for (int i = 0; i < assetGUIDs.Length; i++)
  25. {
  26. assetPaths[i] = AssetDatabase.GUIDToAssetPath(assetGUIDs[0]);
  27. }
  28. allAssetPaths = AssetDatabase.GetAllAssetPaths();
  29. thread = new Thread(new ThreadStart(FindreAssetFerences));
  30. thread.Start();
  31. }
  32. static void FindreAssetFerences()
  33. {
  34. List<string> logInfo = new List<string>();
  35. string path;
  36. string log;
  37. for (int i = 0; i < allAssetPaths.Length; i++)
  38. {
  39. path = allAssetPaths[i];
  40. if (path.EndsWith(".prefab") || path.EndsWith(".unity"))
  41. {
  42. string content = File.ReadAllText(path);
  43. if (content == null)
  44. {
  45. continue;
  46. }
  47. for (int j = 0; j < assetGUIDs.Length; j++)
  48. {
  49. if (content.IndexOf(assetGUIDs[j]) > 0)
  50. {
  51. log = string.Format("{0} 引用了 {1}", path, assetPaths[j]);
  52. logInfo.Add(log);
  53. }
  54. }
  55. }
  56. }
  57. for (int i = 0; i < logInfo.Count; i++)
  58. {
  59. Debug.LogError(logInfo[i]);
  60. }
  61. Debug.LogError("选择对象引用数量:" + logInfo.Count);
  62. Debug.LogError("查找完成");
  63. }
  64. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTM2NTQxMjU_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,293人围观)

还没有评论,来说两句吧...

相关阅读

    相关 unity提取打包资源

    untiy打包资源是不可见的,在代码中需要www加载去提取,当然也有别的方法去提取打包资源,这对于很久远的数据打包资源来说是个很好的方法,因为太久远了就找不到了,只能拿打包资源

    相关 Unity中的引用计数器(RefCount)

    引用计数使用场景: 有一间黑色的屋子,里边有一盏灯。当第一个人进屋的时候灯会打开,之后进来的人则不用再次打开了,因为已经打开过了。当屋子里所有人都离开了的时候,灯则会关闭