Skip to content

Instantly share code, notes, and snippets.

@JVinceW
Last active May 28, 2023 13:46
Show Gist options
  • Save JVinceW/54376d50e4c897d46d5b17bed847c3d2 to your computer and use it in GitHub Desktop.
Save JVinceW/54376d50e4c897d46d5b17bed847c3d2 to your computer and use it in GitHub Desktop.
Find missing scripts recursively and remove it editor
/*
Ref: https://forum.unity.com/threads/remove-all-missing-reference-behaviours.286808/#post-3113536
https://pastebin.com/raw/DLuE2Ze9
*/
using UnityEditor;
using UnityEngine;
namespace FLGCoreEditor.Utilities
{
public class FindMissingScriptsRecursivelyAndRemove : EditorWindow
{
private static int _goCount;
private static int _componentsCount;
private static int _missingCount;
private static bool _bHaveRun;
[MenuItem("FLGCore/Editor/Utility/FindMissingScriptsRecursivelyAndRemove")]
public static void ShowWindow()
{
GetWindow(typeof(FindMissingScriptsRecursivelyAndRemove));
}
public void OnGUI()
{
if (GUILayout.Button("Find Missing Scripts in selected GameObjects"))
{
FindInSelected();
}
if (!_bHaveRun) return;
EditorGUILayout.TextField($"{_goCount} GameObjects Selected");
if(_goCount>0) EditorGUILayout.TextField($"{_componentsCount} Components");
if(_goCount>0) EditorGUILayout.TextField($"{_missingCount} Deleted");
}
private static void FindInSelected()
{
var go = Selection.gameObjects;
_goCount = 0;
_componentsCount = 0;
_missingCount = 0;
foreach (var g in go)
{
FindInGo(g);
}
_bHaveRun = true;
Debug.Log($"Searched {_goCount} GameObjects, {_componentsCount} components, found {_missingCount} missing");
AssetDatabase.SaveAssets();
}
private static void FindInGo(GameObject g)
{
_goCount++;
var components = g.GetComponents<Component>();
var r = 0;
for (var i = 0; i < components.Length; i++)
{
_componentsCount++;
if (components[i] != null) continue;
_missingCount++;
var s = g.name;
var t = g.transform;
while (t.parent != null)
{
s = t.parent.name +"/"+s;
t = t.parent;
}
Debug.Log ($"{s} has a missing script at {i}", g);
var serializedObject = new SerializedObject(g);
var prop = serializedObject.FindProperty("m_Component");
prop.DeleteArrayElementAtIndex(i-r);
r++;
serializedObject.ApplyModifiedProperties();
}
foreach (Transform childT in g.transform)
{
FindInGo(childT.gameObject);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment