using UnityEngine;
using UnityEditor;

public class RemoveMissingScriptsTool : MonoBehaviour
{
    [MenuItem("Tools/Remove Missing Scripts")]
    private static void RemoveAllMissingScripts()
    {
        // 计数器，用来记录删除了多少 missing script
        int missingScriptCount = 0;

        // 获取场景中所有的 GameObject
        GameObject[] allGameObjects = FindObjectsOfType<GameObject>();

        // 遍历每个GameObject
        foreach (GameObject go in allGameObjects)
        {
            // 找到GameObject上所有的组件
            Component[] components = go.GetComponents<Component>();

            // 创建一个临时数组来存储组件
            for (int i = 0; i < components.Length; i++)
            {
                if (components[i] == null)
                {
                    // 发现missing script，删除它
                    Undo.RegisterCompleteObjectUndo(go, "Remove Missing Scripts"); // 注册撤销操作
                    GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);   // 删除 missing script
                    missingScriptCount++;
                }
            }
        }

        // 输出删除结果
        Debug.Log($"Removed {missingScriptCount} missing scripts from the scene.");

        // 提示用户删除成功
        EditorUtility.DisplayDialog("Missing Scripts Removed", $"Removed {missingScriptCount} missing scripts from the scene.", "OK");
    }
}