Example-Code / Editor Scripts / MissingReferenceFinder.cs
MissingReferenceFinder.cs
Raw
namespace CCG.Bigfoot.Editor
{
    using System.Linq;
    /// <summary>
    /// Provides feature of scanning current scene and printing missing references.
    /// </summary>
    /// <remarks>
    /// Authors: CS
    /// Created: 2024-02-01
    /// </remarks>
    using UnityEditor;
    using UnityEngine;
    public static class MissingReferenceFinder
    {
        private static int _numMissingRefs = 0;

        [MenuItem("Tools/Find Missing references in scene")]
        public static void FindMissingReferences()
        {
            GameObject[] objects = GameObject.FindObjectsOfType<GameObject>();
            foreach (var go in objects)
            {
                var components = go.GetComponents<Component>();

                foreach (var c in components)
                {
                    if (c == null)
                    {
                        Debug.LogError("Missing script found on: " + GetFullObjectPath(go), go);
                        if (go.hideFlags.HasFlag(HideFlags.HideInInspector))
                        {
                            Debug.LogError("Hidden go detected on " + go.name, go);
                            //go.hideFlags = HideFlags.None; //--Enable this line to show the hidden go's so you can manage them.
                        }
                        _numMissingRefs++;
                    }
                    else
                    {
                        SerializedObject so = new SerializedObject(c);
                        var sp = so.GetIterator();

                        while (sp.NextVisible(true))
                        {
                            if (sp.propertyType != SerializedPropertyType.ObjectReference)
                            {
                                continue;
                            }

                            if (sp.objectReferenceValue == null && sp.objectReferenceInstanceIDValue != 0)
                            {
                                ShowError(go, sp.name);
                                _numMissingRefs++;
                            }
                        }
                    }
                }
            }
            Debug.Log("Finished. Found " + _numMissingRefs + " missing references on " + objects.Count() + " GO's.");
            _numMissingRefs = 0;
        }

        private static void ShowError(GameObject go, string propertyName)
        {
            Debug.LogError("Missing reference found in: " + GetFullObjectPath(go) + ", Property : " + propertyName, go);
        }

        private static string GetFullObjectPath(GameObject go)
        {
            return go.transform.parent == null ? go.name : GetFullObjectPath(go.transform.parent.gameObject) + "/" + go.name;
        }
    }
}