原理:
Unity 中的每个物体都有一个唯一 GUID , Prefab, Scene, Material 里面都存有引用到的 GUID 。所以,我们只要在相应的文件内容中找到该图片的 GUID 就表明该文件引用到了该图片。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.IO;
public class FindReferencesEditorWindow : EditorWindow {
[MenuItem("Tools/Find References")] public static void FindReferences() { FindReferencesEditorWindow window = (FindReferencesEditorWindow)EditorWindow .GetWindow(typeof(FindReferencesEditorWindow), false, "Find References", true); window.Show(); } private static Object findObj; private List<Object> result = new List<Object>();
private Vector2 scrollPos = new Vector2(); private bool checkPrefab = true; private bool checkScene = true; private bool checkMaterial = true;
private void OnGUI() { EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal(); findObj = EditorGUILayout.ObjectField(findObj, typeof(Object), true); if (GUILayout.Button("Find", GUILayout.Width(100))) { result.Clear(); if (findObj == null) { return; } string assetPath = AssetDatabase.GetAssetPath(findObj); string assetGuid = AssetDatabase.AssetPathToGUID(assetPath); string filter = ""; if (checkPrefab) { filter += "t:Prefab "; } if (checkScene) { filter += "t:Scene "; } if (checkMaterial) { filter += "t:Material "; } filter = filter.Trim(); Debug.Log("Filter = " + filter); if (!string.IsNullOrEmpty(filter)) { string[] guids = AssetDatabase.FindAssets(filter, new[] { "Assets" }); int len = guids.Length; for (int i = 0; i < len; i++) { string filePath = AssetDatabase.GUIDToAssetPath(guids[i]); bool cancel = EditorUtility.DisplayCancelableProgressBar("Finding ...", filePath, i * 1.0f / len); if (cancel) { break; } try { string content = File.ReadAllText(filePath); if(content.Contains(assetGuid)) { Object fileObject = AssetDatabase.LoadAssetAtPath(filePath, typeof(Object)); result.Add(fileObject); } } catch (System.Exception e) { Debug.LogWarning(filePath + "\n" + e.ToString()); } } EditorUtility.ClearProgressBar(); } } EditorGUILayout.EndHorizontal(); checkPrefab = EditorGUILayout.Toggle("Check Prefab : ", checkPrefab); checkScene = EditorGUILayout.Toggle("Check Scene : ", checkScene); checkMaterial = EditorGUILayout.Toggle("Check Material : ", checkMaterial); EditorGUILayout.LabelField("Result Count = " + result.Count);
EditorGUILayout.Space();
scrollPos = EditorGUILayout.BeginScrollView(scrollPos); for (int i = 0; i < result.Count; i++) { EditorGUILayout.ObjectField(result[i], typeof(Object), true); } EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical(); } }
|