using UnityEditor; using UnityEngine; public class RemoveMissingScripts : EditorWindow { [MenuItem("Tools/Remove Missing Scripts")] static void RemoveMissingScriptsFromAllGameObjects() { // 获取所有场景中的 GameObject GameObject[] allObjects = GameObject.FindObjectsOfType(); foreach (GameObject obj in allObjects) { // 如果是预制体实例化的对象 if (PrefabUtility.GetPrefabAssetType(obj) != PrefabAssetType.NotAPrefab) { // 在预制体实例中操作 RemoveMissingScriptsFromPrefab(obj); } else { // 在场景中的对象中删除丢失的脚本 RemoveMissingScriptsFromGameObject(obj); } } // 刷新编辑器 AssetDatabase.SaveAssets(); EditorUtility.DisplayDialog("Completed", "Removed missing scripts from all GameObjects and Prefabs.", "OK"); } // 删除场景中的丢失脚本组件 static void RemoveMissingScriptsFromGameObject(GameObject obj) { Component[] components = obj.GetComponents(); foreach (var component in components) { if (component == null) { Undo.DestroyObjectImmediate(obj.GetComponent(component.GetType())); Debug.Log("Removed missing script from: " + obj.name); } } } // 删除预制体中的丢失脚本组件 static void RemoveMissingScriptsFromPrefab(GameObject prefabInstance) { // 确保进入编辑模式 if (!PrefabUtility.IsPartOfPrefabAsset(prefabInstance)) { Debug.LogWarning("The selected object is not a prefab instance."); return; } // 获取预制体的根实例及其所有组件 Component[] components = prefabInstance.GetComponentsInChildren(true); foreach (var component in components) { if (component == null) { // 在编辑预制时删除丢失的组件 Undo.DestroyObjectImmediate(prefabInstance.GetComponent(component.GetType())); Debug.Log("Removed missing script from prefab instance: " + prefabInstance.name); } } // 确保对预制体的修改被保存 PrefabUtility.ApplyPrefabInstance(prefabInstance, InteractionMode.UserAction); } }