RemoveMissingScripts.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using UnityEditor;
  2. using UnityEngine;
  3. public class RemoveMissingScripts : EditorWindow
  4. {
  5. [MenuItem("Tools/Remove Missing Scripts")]
  6. static void RemoveMissingScriptsFromAllGameObjects()
  7. {
  8. // 获取所有场景中的 GameObject
  9. GameObject[] allObjects = GameObject.FindObjectsOfType<GameObject>();
  10. foreach (GameObject obj in allObjects)
  11. {
  12. // 如果是预制体实例化的对象
  13. if (PrefabUtility.GetPrefabAssetType(obj) != PrefabAssetType.NotAPrefab)
  14. {
  15. // 在预制体实例中操作
  16. RemoveMissingScriptsFromPrefab(obj);
  17. }
  18. else
  19. {
  20. // 在场景中的对象中删除丢失的脚本
  21. RemoveMissingScriptsFromGameObject(obj);
  22. }
  23. }
  24. // 刷新编辑器
  25. AssetDatabase.SaveAssets();
  26. EditorUtility.DisplayDialog("Completed", "Removed missing scripts from all GameObjects and Prefabs.", "OK");
  27. }
  28. // 删除场景中的丢失脚本组件
  29. static void RemoveMissingScriptsFromGameObject(GameObject obj)
  30. {
  31. Component[] components = obj.GetComponents<Component>();
  32. foreach (var component in components)
  33. {
  34. if (component == null)
  35. {
  36. Undo.DestroyObjectImmediate(obj.GetComponent(component.GetType()));
  37. Debug.Log("Removed missing script from: " + obj.name);
  38. }
  39. }
  40. }
  41. // 删除预制体中的丢失脚本组件
  42. static void RemoveMissingScriptsFromPrefab(GameObject prefabInstance)
  43. {
  44. // 确保进入编辑模式
  45. if (!PrefabUtility.IsPartOfPrefabAsset(prefabInstance))
  46. {
  47. Debug.LogWarning("The selected object is not a prefab instance.");
  48. return;
  49. }
  50. // 获取预制体的根实例及其所有组件
  51. Component[] components = prefabInstance.GetComponentsInChildren<Component>(true);
  52. foreach (var component in components)
  53. {
  54. if (component == null)
  55. {
  56. // 在编辑预制时删除丢失的组件
  57. Undo.DestroyObjectImmediate(prefabInstance.GetComponent(component.GetType()));
  58. Debug.Log("Removed missing script from prefab instance: " + prefabInstance.name);
  59. }
  60. }
  61. // 确保对预制体的修改被保存
  62. PrefabUtility.ApplyPrefabInstance(prefabInstance, InteractionMode.UserAction);
  63. }
  64. }