使用DeleteArrayElementAtIndex方法删除Missing Script报错:It is not allowed to modify the data property的替代方案

针对高版本UNITY使用DeleteArrayElementAtIndex方法删除Missing Script出现报错:It is not allowed to modify the data property的解决方案:

  • unity在新的版本中
    引入了GameObjectUtility.RemoveMonoBehavioursWithMissingScript方法来移除预置体中的Missing
    Script。网络上使用DeleteArrayElementAtIndex方法批量删除Missing Script会出现It is not allowed to modify the data property这样禁止修改Property的报错,于是对其进行改良使用新的GameObjectUtility.RemoveMonoBehavioursWithMissingScript方法,话不多说,直接上代码
 [MenuItem("MyTools/LgsTools/智能检测/Remove Missing-MonoBehavior Component")]
    static public void RemoveMissComponent()
    {
    	//此处地址为根地址,代码会从这个地址的文件夹下开始遍历里面的所有文件夹的所有预置体以及它的子物体
        string path = Application.dataPath + "/Download";
        string[] getFoder = Directory.GetDirectories(path);
        searchFile(getFoder);
    }

    //递归遍历文件夹
    static public void searchFile(string[] path)
    {
        foreach (string item in path)
        {
            string[] getFile = Directory.GetFiles(item);
            foreach (string file in getFile)
            {
                FileInfo fileInfo = new FileInfo(file);
                if (fileInfo.Extension.Equals(".Prefab", StringComparison.CurrentCultureIgnoreCase))
                {
                    CheckMissMonoBehavior(file);
                }
            }
            string[] getFoder = Directory.GetDirectories(item);
            searchFile(getFoder);
        }
    }

    ///   
    /// 删除一个Prefab上的空脚本  
    ///   
    /// prefab路径 例Assets/Resources/FriendInfo.prefab  
    static void CheckMissMonoBehavior(string path)
    {
        //先截取路径,使路径从ASSETS开始
        int index = path.IndexOf("Assets/", StringComparison.CurrentCultureIgnoreCase);
        string newPath = path.Substring(index);
        GameObject obj = AssetDatabase.LoadAssetAtPath(newPath, typeof(GameObject)) as GameObject;
        //实例化物体
        GameObject go = PrefabUtility.InstantiatePrefab(obj) as GameObject;
        //递归删除
        searchChild(go);
        // 将数据替换到asset

        PrefabUtility.SaveAsPrefabAsset(go, newPath);

        go.hideFlags = HideFlags.HideAndDontSave;
        //删除掉实例化的对象
        DestroyImmediate(go);
    }
    //递归物体的子物体
    static public void searchChild(GameObject gameObject)
    {
        int number = GameObjectUtility.RemoveMonoBehavioursWithMissingScript(gameObject);
        if (gameObject.transform.childCount > 0)
        {
            for (int i = 0; i < gameObject.transform.childCount; i++)
            {
                searchChild(gameObject.transform.GetChild(i).gameObject);
            }
        }
    }
  • 觉得有帮助的可以点个赞谢谢,此方法是暴力递归遍历文件夹下的所有预置体,预置体子物体,大神如有更好的办法还请务必评论区指出。(GameObjectUtility.RemoveMonoBehavioursWithMissingScript方法是论坛一个老哥告知的,在此特此感谢一下)

你可能感兴趣的:(使用DeleteArrayElementAtIndex方法删除Missing Script报错:It is not allowed to modify the data property的替代方案)