Find and remove missing components

public static void RemoveInGo(GameObject g)
{
    var components = g.GetComponents<Component>();
    
    var r = 0;
    
    for (var i = 0; i < components.Length; ++i)
    {
        if (components[i] != null) 
            continue;
        
        var s = g.name;
        var t = g.transform;
        while (t.parent != null) 
        {
            s = t.parent.name +"/"+s;
            t = t.parent;
        }
        
        Debug.Log ($"{s} has a missing script at {i}", g);
        
        var serializedObject = new SerializedObject(g);
        
        var prop = serializedObject.FindProperty("m_Component");
        
        prop.DeleteArrayElementAtIndex(i-r);
        r++;
    
        serializedObject.ApplyModifiedProperties();
    }
    
    foreach (Transform childT in g.transform)
    {
        RemoveInGo(childT.gameObject);
    }
}

官方解决方案可以使用
GameObjectUtility.RemoveMonoBehavioursWithMissingScript

–EOF–

王小兵 /
Published under (CC) BY-NC-SA in categories Unity  tagged with Unity