在Unity中查找缺失的引用

这篇博客是查找unity中缺失引用的一个简单简短的解决方案。你可以从GitHub上获取源码。
缺失引用
一个丢失引用与没有引用(在检视表显示“None”)是完全不同的概念。这些友各种原因造成,比如:把资源文件从Unity编辑器中移除,导致在.meta文件混乱,其中有个指向无效的连接。
主要问题是缺失引用在项目中会被隐藏在某处,只有等运行中找到时已经太晚了。幸运的是,我们编写了编辑器脚本来补救...
 
解决方案:
以防止你也遇到这种问题,下面是查找缺失引用的所有代码:
 
 using System.Collections;
using System.Linq;
using UnityEditor;
using UnityEngine; public class MissingReferencesFinder : MonoBehaviour
{
[MenuItem("Tools/Show Missing Object References in scene", false, )]
public static void FindMissingReferencesInCurrentScene()
{
var objects = GetSceneObjects();
FindMissingReferences(EditorApplication.currentScene, objects);
} [MenuItem("Tools/Show Missing Object References in all scenes", false, )]
public static void MissingSpritesInAllScenes()
{
foreach (var scene in EditorBuildSettings.scenes.Where(s => s.enabled))
{
EditorApplication.OpenScene(scene.path);
FindMissingReferences(scene.path, GetSceneObjects());
}
} [MenuItem("Tools/Show Missing Object References in assets", false, )]
public static void MissingSpritesInAssets()
{
var allAssets = AssetDatabase.GetAllAssetPaths();
var objs = allAssets.Select(a => AssetDatabase.LoadAssetAtPath(a, typeof(GameObject)) as GameObject).Where(a => a != null).ToArray(); FindMissingReferences("Project", objs);
} private static void FindMissingReferences(string context, GameObject[] objects)
{
foreach (var go in objects)
{
var components = go.GetComponents(); foreach (var c in components)
{
if (!c)
{
Debug.LogError("Missing Component in GO: " + FullPath(go), go);
continue;
} SerializedObject so = new SerializedObject(c);
var sp = so.GetIterator(); while (sp.NextVisible(true))
{
if (sp.propertyType == SerializedPropertyType.ObjectReference)
{
if (sp.objectReferenceValue == null
&& sp.objectReferenceInstanceIDValue != )
{
ShowError(context, go, c.GetType().Name, ObjectNames.NicifyVariableName(sp.name));
}
}
}
}
}
} private static GameObject[] GetSceneObjects()
{
return Resources.FindObjectsOfTypeAll()
.Where(go => string.IsNullOrEmpty(AssetDatabase.GetAssetPath(go))
&& go.hideFlags == HideFlags.None).ToArray();
} private const string err = "Missing Ref in: [{3}]{0}. Component: {1}, Property: {2}"; private static void ShowError (string context, GameObject go, string c, string property)
{
Debug.LogError(string.Format(err, FullPath(go), c, property, context), go);
} private static string FullPath(GameObject go)
{
return go.transform.parent == null
? go.name
: FullPath(go.transform.parent.gameObject) + "/" + go.name;
}
}
作者: Lior Tal
上一篇:关于Unity中DOTween插件的使用(专题一)


下一篇:Linux下tomcat启动