Skip to content

Instantly share code, notes, and snippets.

@SolarianZ
Last active July 6, 2023 15:03
Show Gist options
  • Save SolarianZ/33be2d047b99ea225be777a4e3e3f48c to your computer and use it in GitHub Desktop.
Save SolarianZ/33be2d047b99ea225be777a4e3e3f48c to your computer and use it in GitHub Desktop.
{"category": "Unity Engine/Editor/Extensions", "keywords": "Unity, Editor, GameObject, Missing, Script"} Log GameObjects with missing scripts in loaded scenes, remove missing scripts from selected GameObjects recursively in the Unity Editor.
public static class MissingScriptTool
{
[MenuItem("Tools/Bamboo/GameObject/Log GameObjects with Missing Script in Loaded Scenes")]
public static void LogGameObjectsWithMissingScriptInLoadedScenes()
{
var missingScriptCount = 0;
var sceneCount = SceneManager.loadedSceneCount;
for (var i = 0; i < sceneCount; i++)
{
var scene = SceneManager.GetSceneAt(i);
var rootGameObjects = scene.GetRootGameObjects();
foreach (var rootGameObject in rootGameObjects)
{
missingScriptCount += LogMissingScriptsOnGameObjectRecursively(rootGameObject);
}
}
Debug.Log($"Found {missingScriptCount} missing script(s) in loaded scene(s).");
}
public static int LogMissingScriptsOnGameObjectRecursively(GameObject rootGameObject)
{
var missingScriptCount = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(rootGameObject);
if (missingScriptCount > 0)
{
Debug.Log($"Found {missingScriptCount} missing script(s) on {rootGameObject.name}.", rootGameObject);
}
foreach (Transform child in rootGameObject.transform)
{
missingScriptCount += LogMissingScriptsOnGameObjectRecursively(child.gameObject);
}
return missingScriptCount;
}
[MenuItem("Tools/Bamboo/GameObject/Remove Missing Scripts From Selected GameObjects Recursively")]
[MenuItem("GameObject/Bamboo/Remove Missing Scripts Recursively")]
public static void RemoveMissingScriptsFromSelectedGameObjectsRecursively()
{
var selectedGameObjects = Selection.gameObjects;
foreach (var gameObject in selectedGameObjects)
{
Undo.RegisterFullObjectHierarchyUndo(gameObject, nameof(RemoveMissingScriptsRecursively));
RemoveMissingScriptsRecursively(gameObject);
}
}
[MenuItem("Tools/Bamboo/GameObject/Remove Missing Scripts From Selected GameObjects Recursively", validate = true)]
[MenuItem("GameObject/Bamboo/Remove Missing Scripts Recursively", validate = true)]
public static bool RemoveMissingScriptsFromSelectedGameObjectsRecursivelyValidate()
{
return Selection.gameObjects.Length > 0;
}
public static void RemoveMissingScriptsRecursively(this GameObject gameObject)
{
var removedCount = GameObjectUtility.RemoveMonoBehavioursWithMissingScript(gameObject);
if (removedCount > 0)
{
Debug.Log($"Removed {removedCount} missing script(s) from {gameObject.name}.", gameObject);
}
foreach (Transform child in gameObject.transform)
{
child.gameObject.RemoveMissingScriptsRecursively();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment