首页 >Unity3D频道 >【Unity杂文】 > Unity3D研究院之查找资源被哪里引用了
2016
06-29

Unity3D研究院之查找资源被哪里引用了

Unity提供了一个方法 AssetDatabase.GetDependencies(),但是它只能查找这个资源引用了那些资源。 但是我想要的是查找某个资源被那些资源引用了,这是两种相反的查找公式。 其实网上也有很多这样的插件了,似乎代码量都太多了。昨天晚上加班时脑洞打开,想到了一个简单的方法。通过GUID全局搜索匹配。。几行代码就能搞定~~

如下图所示,右键随便选择一个资源,点击 Find References。

Snip20160629_2

然后开始匹配资源。

Snip20160629_3

匹配结束后会把匹配到的资源Log出来。以下代码直接放到你的工程里就可以直接用。

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class FindReferences
{
  
    [MenuItem("Assets/Find References", false, 10)]
    static private void Find()
    {
        EditorSettings.serializationMode = SerializationMode.ForceText;
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (!string.IsNullOrEmpty(path))
        {
            string guid = AssetDatabase.AssetPathToGUID(path);
            List withoutExtensions = new List(){".prefab",".unity",".mat",".asset"};
            string[] files = Directory.GetFiles(Application.dataPath, "*.*", SearchOption.AllDirectories)
                .Where(s => withoutExtensions.Contains(Path.GetExtension(s).ToLower())).ToArray();
            int startIndex = 0;

            EditorApplication.update = delegate()
            {
                string file = files[startIndex];
            
                 bool isCancel = EditorUtility.DisplayCancelableProgressBar("匹配资源中", file, (float)startIndex / (float)files.Length);

                if (Regex.IsMatch(File.ReadAllText(file), guid))
                {
                    Debug.Log(file, AssetDatabase.LoadAssetAtPath<Object>(GetRelativeAssetsPath(file)));
                }

                startIndex++;
                if (isCancel || startIndex >= files.Length)
                {
                    EditorUtility.ClearProgressBar();
                    EditorApplication.update = null;
                    startIndex = 0;
                    Debug.Log("匹配结束");
                }

            };
        }
    }

    [MenuItem("Assets/Find References", true)]
    static private bool VFind()
    {
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        return (!string.IsNullOrEmpty(path));
    }

    static private string GetRelativeAssetsPath(string path)
    {
        return "Assets" + Path.GetFullPath(path).Replace(Path.GetFullPath(Application.dataPath), "").Replace('\', '/');
    }
}

 

美中不足的地方就是查找速度了。。其实正则表达式匹配的速度还是很快,慢的地方是File.ReadAllText(file) 如果大家有更好的办法,欢迎推荐~

 

今天我无意发现了一个更快的方法,可惜只能在mac上用。比我上面的方法要快N倍啊,快的丧心病狂啊~欢迎大家用啊~~。。。

https://gist.github.com/jringrose/617d4cba87757591ce28

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;

public class FindProject {
	
	#if UNITY_EDITOR_OSX
	
	[MenuItem("Assets/Find References In Project", false, 2000)]
	private static void FindProjectReferences()
	{
		string appDataPath = Application.dataPath;
		string output = "";
		string selectedAssetPath = AssetDatabase.GetAssetPath (Selection.activeObject);
		List<string> references = new List<string>();
		
		string guid = AssetDatabase.AssetPathToGUID (selectedAssetPath);
		
		var psi = new System.Diagnostics.ProcessStartInfo();
		psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
		psi.FileName = "/usr/bin/mdfind";
		psi.Arguments = "-onlyin " + Application.dataPath + " " + guid;
		psi.UseShellExecute = false;
		psi.RedirectStandardOutput = true;
		psi.RedirectStandardError = true;
		
		System.Diagnostics.Process process = new System.Diagnostics.Process();
		process.StartInfo = psi;
		
		process.OutputDataReceived += (sender, e) => {
			if(string.IsNullOrEmpty(e.Data))
				return;
			
			string relativePath = "Assets" + e.Data.Replace(appDataPath, "");
			
			// skip the meta file of whatever we have selected
			if(relativePath == selectedAssetPath + ".meta")
				return;
			
			references.Add(relativePath);
			
		};
		process.ErrorDataReceived += (sender, e) => {
			if(string.IsNullOrEmpty(e.Data))
				return;
			
			output += "Error: " + e.Data + "n";
		};
		process.Start();
		process.BeginOutputReadLine();
		process.BeginErrorReadLine();
		
		process.WaitForExit(2000);
		
		foreach(var file in references){
			output += file + "n";
			Debug.Log(file, AssetDatabase.LoadMainAssetAtPath(file));
		}
		
		Debug.LogWarning(references.Count + " references found for object " + Selection.activeObject.name + "nn" + output);
	}
	
	#endif

 

最后编辑:
作者:雨松MOMO
专注移动互联网,Unity3D游戏开发
捐 赠写博客不易,如果您想请我喝一杯星巴克的话?就进来看吧!

Unity3D研究院之查找资源被哪里引用了》有 23 条评论

  1. 冬晓说:

    https://zhuanlan.zhihu.com/p/48181495 此方法更快,相差10倍以上的速度

  2. 哎柠檬茶说:

    这个好像确实比较恐怖。相当于是把meta文件直接读了。单个资源尚可。我想查找项目中所有的没有被引用的资源,,我再想想办法

  3. ice说:

    用多线程读取文件的方式就可以极快的提高速度啦

  4. 猎人说:

    雨神,我在编辑器中想通过AssetDatabase.GetDependencies()获取依赖的资源然后加载这些依赖资源,不知何故加载不出来,能帮我看看下面这段代码吗?public void main(){EditorSettings.serializationMode = SerializationMode.ForceText;byte[] filebytes = File.ReadAllBytes(filename);AssetBundle ab = AssetBundle.LoadFromMemory(filebytes);string[] names = ab.GetAllAssetNames();string[] dependencies = AssetDatabase.GetDependencies(names);for (int i = 0; i < dependencies.Length; i){UnityEngine.Object obj = ab.LoadAsset(dependencies Unity3D研究院之查找资源被哪里引用了 - 雨松MOMO程序研究院 - 1 );//为何这里获取不到呢 obj一直是null if (obj != null)Debug.log(obj.name);}}

  5. 猎人说:

    雨神,我在编辑器中想通过AssetDatabase.GetDependencies()获取依赖的资源然后加载这些依赖资源,不知何故加载不出来,能帮我看看下面这段代码吗?public void main(){ EditorSettings.serializationMode = SerializationMode.ForceText; byte[] filebytes = File.ReadAllBytes(filename); AssetBundle ab = AssetBundle.LoadFromMemory(filebytes); string[] names = ab.GetAllAssetNames(); string[] dependencies = AssetDatabase.GetDependencies(names); for (int i = 0; i < dependencies.Length; ++i) { UnityEngine.Object obj = ab.LoadAsset(dependencies Unity3D研究院之查找资源被哪里引用了 - 雨松MOMO程序研究院 - 1 );//为何这里获取不到呢 obj一直是null if (obj != null) Debug.log(obj.name); }}

  6. Ajax说:

    可以直接用grep扫所有的文件就能大概找出来了

  7. 刘国栋说:

    雨神,如何判断场景中是否存在一个已知的但是setactive(false)对象?因为,这个对象的active是false,所以没办法用find来查找,不知道怎么找到它

  8. 奔跑的蜗牛说:

    unity 5.3.4 右键并没有 Find References啊

  9. 陈伟利说:

    unity5.3.5 怎么动态加载视频。视频用ogg和ogv格式都不行,请问大神用什么格式

  10. darling说:

    为啥scripting api里面查不到 EditorSettings。用的unity5.34。代码里是有的.

  11. 单细胞说:

    感谢雨松!

留下一个回复

你的email不会被公开。 必填项已用 * 标注。