using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using UnityEditor; using UnityEngine; public static class AssetRefSearchTool { #if UNITY_EDITOR static string[] assetGUIDs; static string[] assetPaths; static string[] allAssetPaths; static Thread thread; [MenuItem("项目工具/资源检查/查找资源被引用(Project选中的)", false)] static void FindAssetRefMenu() { if (Selection.assetGUIDs.Length == 0) { Debug.Log("请先选择任意一个组件,再击此菜单"); return; } assetGUIDs = Selection.assetGUIDs; assetPaths = new string[assetGUIDs.Length]; for (int i = 0; i < assetGUIDs.Length; i++) { assetPaths[i] = AssetDatabase.GUIDToAssetPath(assetGUIDs[i]); } allAssetPaths = AssetDatabase.GetAllAssetPaths(); thread = new Thread(new ThreadStart(FindAssetRef)); thread.Start(); } [MenuItem("Assets/在UIPrefabs中查找被引用的资源", false, -99)] static void FindAssetInUIPrefabs() { List logInfo = new List(); string log; if (Selection.assetGUIDs.Length == 0) { Debug.Log("请先选择任意一个组件,再击此菜单"); return; } assetGUIDs = Selection.assetGUIDs; assetPaths = new string[assetGUIDs.Length]; for (int i = 0; i < assetGUIDs.Length; i++) { assetPaths[i] = AssetDatabase.GUIDToAssetPath(assetGUIDs[i]); } DirectoryInfo directoryInfo = new DirectoryInfo("Assets/GameAssets/Prefabs/UI"); List files = new List(); ListFilesRecursively(directoryInfo, files); foreach (var fileInfo in files) { if (!fileInfo.FullName.EndsWith(".prefab") && !fileInfo.FullName.EndsWith(".asset")) continue; string content = File.ReadAllText(fileInfo.FullName); if (content == null) continue; for (int j = 0; j < assetGUIDs.Length; j++) { if (content.IndexOf(assetGUIDs[j]) > 0) { log = string.Format("{0} 引用了 {1}", fileInfo.FullName, assetPaths[j]); logInfo.Add(log); } } } for (int i = 0; i < logInfo.Count; i++) { Debug.Log(logInfo[i]); } Debug.Log("选择对象引用数量:" + logInfo.Count); Debug.Log("查找完成"); } static void FindAssetRef() { Debug.Log(string.Format("开始查找引用{0}的资源。", string.Join(",", assetPaths))); List logInfo = new List(); string path; string log; for (int i = 0; i < allAssetPaths.Length; i++) { path = allAssetPaths[i]; if (path.EndsWith(".prefab") || path.EndsWith(".unity")) { string content = File.ReadAllText(path); if (content == null) { continue; } for (int j = 0; j < assetGUIDs.Length; j++) { if (content.IndexOf(assetGUIDs[j]) > 0) { log = string.Format("{0} 引用了 {1}", path, assetPaths[j]); logInfo.Add(log); } } } } for (int i = 0; i < logInfo.Count; i++) { Debug.Log(logInfo[i]); } Debug.Log("选择对象引用数量:" + logInfo.Count); Debug.Log("查找完成"); } public static void ListFilesRecursively(DirectoryInfo directory, List files) { // 获取当前目录下的所有文件 files.AddRange(directory.GetFiles().ToArray()); // 递归处理子目录 DirectoryInfo[] subDirectories = directory.GetDirectories(); foreach (var subDirectory in subDirectories) { ListFilesRecursively(subDirectory, files); } } #endif }