Last active
August 17, 2024 15:26
-
-
Save to-osaki/d70b7fd597053ec015dc0b8964e74b1b to your computer and use it in GitHub Desktop.
Unity Find missing references
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEditor; | |
public class FindMissingEditor : EditorWindow | |
{ | |
[MenuItem(itemName: "Menu/Find Missing References")] | |
public static void Open() | |
{ | |
EditorWindow.GetWindow<FindMissingEditor>("Find Missing References").Show(); | |
} | |
private void OnGUI() | |
{ | |
if (GUILayout.Button("Missing in Hierarchy")) | |
{ | |
int sceneCount = UnityEngine.SceneManagement.SceneManager.sceneCount; | |
for (int i = 0; i < sceneCount; ++i) | |
{ | |
var scene = UnityEngine.SceneManagement.SceneManager.GetSceneAt(i); | |
var roots = scene.GetRootGameObjects(); | |
foreach (var go in roots) | |
{ | |
FindMissing(go); | |
} | |
} | |
} | |
if (GUILayout.Button("Missing in Prefabs")) | |
{ | |
string[] guids = AssetDatabase.FindAssets("t:prefab"); | |
for (int i = 0; i < guids.Length; ++i) | |
{ | |
var path = AssetDatabase.GUIDToAssetPath(guids[i]); | |
var go = AssetDatabase.LoadAssetAtPath<GameObject>(path); | |
if (go != null) | |
{ | |
FindMissing(go); | |
} | |
} | |
} | |
} | |
private void FindMissing(GameObject go) | |
{ | |
var transforms = go.GetComponentsInChildren<Transform>(); | |
foreach (var t in transforms) | |
{ | |
int missingScripts = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(t.gameObject); | |
if (missingScripts > 0) | |
{ | |
Debug.LogError($"{t.gameObject.name} has missing script(s)", t.gameObject); | |
} | |
var components = t.gameObject.GetComponents<MonoBehaviour>(); | |
foreach (var c in components) | |
{ | |
if (c == null) { continue; } | |
var serializedObject = new SerializedObject(c); | |
var it = serializedObject.GetIterator(); | |
while (it.NextVisible(true)) | |
{ | |
if (it.propertyType == SerializedPropertyType.ObjectReference) | |
{ | |
if (it.objectReferenceValue == null && it.objectReferenceInstanceIDValue != 0) | |
{ | |
Debug.LogError($"{t.gameObject.name}.{c.GetType().Name}.{it.displayName} has missing reference", c); | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment