一个很常用的方法
却越来越多坑。。。。
void DeleteMissingComp(GameObject obj)
{
//一开始网上抄了这段代码,但是 for j 的倒装一下也是不会的吗??
var components = obj.GetComponents<Component>();
SerializedObject so=new SerializedObject(obj);
var soProperties = so.FindProperty("m_Component");
for (int j = 0; j < components.Length; j++)
{
if (components[j] == null)
{
soProperties.DeleteArrayElementAtIndex(j-r);
Debug.LogError("清除了物体:"+obj.name +" 的一个missing脚本");
r++;
}
}
}
最终的代码:
public class DeleteMissingScript
{
[MenuItem("Tools/删除Missing脚本(不可还原)")]
public static void StartDelete()
{
var obj = Selection.activeGameObject;
if (obj == null) return;
// GameObjectUtility.RemoveMonoBehavioursWithMissingScript(obj);
// //DeleteMissingComp(obj);
DeleteRecursive(obj, (go) =>
{
GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
});
}
/// <summary>
/// 第二次,还是想的太简单,这第三次,写的方法,才是对的
/// </summary>
/// <param name="obj"></param>
/// <param name="doDelete"></param>
static void DeleteRecursive(GameObject obj,System.Action<GameObject> doDelete)
{
doDelete(obj);
for (int i = 0; i < obj.transform.childCount; i++)
{
DeleteRecursive(obj.transform.GetChild(i).gameObject,doDelete);
}
}
/// <summary>
/// 后来发现这段代码是从网上国外论坛抄过来的。。。现在没用了;
/// 论坛来源:https://forum.unity.com/threads/how-to-remove-missing-scripts-in-a-prefab.569842/
/// </summary>
/// <param name="obj"></param>
static void DeleteMissingComp(GameObject obj)
{
var components = obj.GetComponents<Component>();
SerializedObject so=new SerializedObject(obj);
var soProperties = so.FindProperty("m_Component");
for (int j = components.Length-1;j>=0; j--)
{
if (components[j] == null)
{
soProperties.DeleteArrayElementAtIndex(j);
}
}
}
}
以上代码请放在Editor目录下
还是可以重新改一下代码的,可以多选,再删除 Missing
[MenuItem("Tools/删除Missing脚本(不可还原)")]
public static void StartDelete()
{
//第四次写,可以选择多个obj 然后删除
var objs = Selection.objects;
foreach (var obj in objs)
{
GameObject gameObject = obj as GameObject;
if (gameObject != null)
{
DeleteRecursive(gameObject, (go) =>
{
GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
});
}
}
}
参考自: