using UnityEngine; using System.Collections; using UnityEditor; using UnityEngine.SceneManagement; using System.Collections.Generic; using System.IO; using System.Linq; public class RemoveMissingScripts : EditorWindow { Vector2 scrollPos = Vector2.zero; List pathList = new List(); List missObj = new List(); private void CleanupMissingScripts() { foreach (GameObject obj in missObj) { // var components = obj.GetComponents(); // var serializedObject = new SerializedObject(obj); var count = GameObjectUtility.RemoveMonoBehavioursWithMissingScript(obj); // if (count > 0) Debug.LogFormat("清空空脚本:{0}", count); // serializedObject.ApplyModifiedProperties(); EditorUtility.SetDirty(obj); } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } private void CheckMissingScripts() { List withoutExtensions = new List() { ".prefab" }; string[] files = Directory.GetFiles(Application.dataPath, "*.*", SearchOption.AllDirectories) .Where(s => withoutExtensions.Contains(Path.GetExtension(s).ToLower())).ToArray(); int count = 0; foreach (string fileName in files) { count++; EditorUtility.DisplayProgressBar("Processing...", "搜寻所有Prefab....", count / files.Length); string fixedFileName = fileName.Replace("\\", "/"); int index = fixedFileName.IndexOf("Assets"); fixedFileName = fixedFileName.Substring(index); pathList.Add(fixedFileName); } EditorUtility.ClearProgressBar(); int count2 = 0; foreach (string path in pathList) { count2++; EditorUtility.DisplayProgressBar("Processing...", "遍历丢失脚本Prefab中....", count / pathList.Count); GameObject obj = (GameObject)AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)); checkMissing(obj); getAllChild(obj); } EditorUtility.ClearProgressBar(); } void getAllChild(GameObject go) { foreach (Transform child in go.transform) { checkMissing(child.gameObject); getAllChild(child.gameObject); } } void checkMissing(GameObject go) { var components = go.GetComponents(); for (int j = 0; j < components.Length; j++) { if (components[j] == null) { missObj.Add(go.gameObject); continue; } } } void OnGUI() { scrollPos = EditorGUILayout.BeginScrollView(scrollPos); if (GUILayout.Button("[查找所有Prefab上的Miss脚本]", GUILayout.Width(300))) { pathList = new List(); missObj = new List(); CheckMissingScripts(); } EditorGUILayout.Space(); if (GUILayout.Button("[删除所有Prefab上的Miss脚本]", GUILayout.Width(300))) { CleanupMissingScripts(); } EditorGUILayout.Space(); EditorGUILayout.Space(); foreach (GameObject obj in missObj) { EditorGUILayout.ObjectField(obj, typeof(GameObject), false); } EditorGUILayout.EndScrollView(); } [MenuItem("程序/移除丢失的脚本")] public static void RemoveMissingScript() { EditorWindow.GetWindow("移除丢失的脚本").Show(); } }