Unity最新一键清理Prefab中所有MissingComponent
因为老的API Properties.DeleteArrayElementAtIndex(propertyIndex);提示没权限修改,
而unity提供了新的API GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go); 更方便移除丢失的组件,需要遍历物体下面所有子节点,否则无法移除子节点的丢失组件。
于是重新整理了下清理的编辑器代码,直接贴上:
1 using System; 2 using UnityEngine; 3 using UnityEditor; 4 5 public class ResTool : Editor 6 { 7 [MenuItem("Tools/清理prefab中所有Missing的脚本")] 8 public static void ClearAllPrefabMissingComponents() 9 { 10 EditorUtility.DisplayProgressBar("Modify Prefab", "Please wait...", 0); 11 string[] assetGUIDs = AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Res/Prefab" }); 12 try 13 { 14 for (int i = 0; i < assetGUIDs.Length; i++) 15 { 16 string path = AssetDatabase.GUIDToAssetPath(assetGUIDs[i]); 17 // Debug.Log($"path:{path}"); 18 GameObject pre = PrefabUtility.LoadPrefabContents(path); 19 20 DeleteRecursive(pre, (go) => 21 { 22 GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go); 23 }); 24 PrefabUtility.SaveAsPrefabAssetAndConnect(pre, path, InteractionMode.AutomatedAction); 25 26 EditorUtility.DisplayProgressBar($"清理Prefab丢失组件", $"当前{pre}, {i}/{assetGUIDs.Length}", i / (float)assetGUIDs.Length); 27 } 28 } 29 catch (Exception e) 30 { 31 Debug.LogError($"{e}"); 32 } 33 34 AssetDatabase.SaveAssets(); 35 EditorUtility.ClearProgressBar(); 36 AssetDatabase.Refresh(); 37 } 38 39 /// <summary> 40 /// 遍历所有子节点 41 /// </summary> 42 /// <param name="obj"></param> 43 /// <param name="action"></param> 44 static void DeleteRecursive(GameObject obj, Action<GameObject> action) 45 { 46 action(obj); 47 48 for (int i = 0; i < obj.transform.childCount; i++) 49 { 50 DeleteRecursive(obj.transform.GetChild(i).gameObject, action); 51 } 52 53 } 54 55 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!