查找当前场景中所有丢失的脚本所在的层级信息和所处组件位置

    //查找当前场景中,所有丢失的脚本
    //删除空脚本
    public class DeleteNullScript
    {
        [MenuItem("Tool/DeleteNullScript")]
        static void Delete()
        {
            if (Selection.gameObjects.Length == 0)
            {
                Debug.Log("请选择需要删除空脚本的游戏对象");
                return;
            }
            for (int i = 0; i < Selection.gameObjects.Length; i++)
            {
                var gameObject = Selection.gameObjects[i];
                var components = gameObject.GetComponents<Component>();

                //序列化当前选中的游戏对象
                var serializedObject = new SerializedObject(gameObject);
                //获得序列化属性
                var prop = serializedObject.FindProperty("m_Component");

                int r = 0;
                for (int j = 0; j < components.Length; j++)
                {
                    if (components[j] == null)
                    {
                        //删除当前属性组件
                        prop.DeleteArrayElementAtIndex(j - r);
                        //增加删除组件数量
                        r++;
                    }
                }
                Debug.Log("删除空脚本数量: " + r);

                //应用属性的改变到当前游戏对象
                serializedObject.ApplyModifiedProperties();
                EditorUtility.SetDirty(gameObject);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/itsxwz/article/details/81273483