Unity Editor 遍历指定文件夹下的所有prefab

这篇具有很好参考价值的文章主要介绍了Unity Editor 遍历指定文件夹下的所有prefab。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

适用场景:

                 查找指定文件夹下所有的prefab并找到所有引用的图片及路径。

步骤分析:

                1、通过guid获取资源路径

                2、获取文件夹中包含后缀为.prefab的路径

                3、编辑器下加载该资源(如果对资源有编辑的话需要在资源加载前加上 开始资源编辑AssetDatabase.StartAssetEditing()  和操作结束后加上 结束资源编辑AssetDatabase.StopAssetEditing())

                4、遍历prefab找到身上带有Image组件的物体,获取iamge.sprite的路径及图片大小信息

                5、将这些信息写入本地,方便资源打包管理

实现代码:

[MenuItem("UnityTools/GetComponentTools/获取预制件图片路径及大小")]
    public static void GetTexturePathOfSize()
    {
        //通过guid获取资源路径
        string guid = Selection.assetGUIDs[0];
        var selectPath = AssetDatabase.GUIDToAssetPath(guid);
        List<string> dirs = new List<string>();
        GetPrefabsDirs(selectPath, ref dirs);
    }

    private static void GetPrefabsDirs(string dirPath, ref List<string> dirs)
    {
        //开始资源编辑
        AssetDatabase.StartAssetEditing();
        
        foreach (string path in Directory.GetFiles(dirPath))
        {
            //获取所有文件夹中包含后缀为 .prefab 的路径
            if (System.IO.Path.GetExtension(path) == ".prefab" && path.IndexOf(@"UI\Slots") == -1)
            {
                dirs.Add(path.Substring(path.IndexOf("Asset")));
                string final_path = path.Substring(path.IndexOf("Asset")).Replace(@"\", "/");
                GameObject prefab = AssetDatabase.LoadAssetAtPath(final_path, typeof(System.Object)) as GameObject;
                
                foreach(Transform child in prefab.GetComponentsInChildren<Transform>(true))
                {
                    if (child.GetComponent<Image>() && child.GetComponent<Image>().sprite != null)
                    {
                        var sp = child.GetComponent<Image>().sprite;
                        
                        var assetPath = AssetDatabase.GetAssetPath(sp);
                        
                        WriteMcImagePath($"预制件路径:{GetChildPaht(child)}, 图片路径:{assetPath}, 图片大小:{GetTxtureSize(assetPath)}Mb");
                    }
                }
            }
        }         
        if (Directory.GetDirectories(dirPath).Length > 0)  //遍历所有文件夹
        {
            foreach (string path in Directory.GetDirectories(dirPath))
            {
                GetDirsImageSprite(path, ref dirs);
            }
        }
        //结束资源编辑
        AssetDatabase.StopAssetEditing();
    }

    /// <summary>
    /// 获取文件大小
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static double GetTxtureSize(string path)
    {
        FileInfo fileInfo = new FileInfo(path);
        double length = Convert.ToDouble(fileInfo.Length);
        double Size = length / 2048;
        return Size;
    }

    /// <summary>
    /// 获取当前子物体在父物体中的路径
    /// </summary>
    /// <param name="_target"></param>
    /// <returns></returns>
    public static string GetChildPaht(Transform _target)
    {
        List<Transform> listPath = new List<Transform>();
        listPath.Add(_target);
        bool isCheck = false;
        string path = "";
        while (!isCheck)
        {
            if (listPath[0].parent != null)
            {
                Transform currentTarget = listPath[0].parent;
                listPath.Insert(0,currentTarget);
            }
            else
            {
                isCheck = true;
            }
        }

        for (int i = 0; i < listPath.Count; i++)
        {
            path += listPath[i].name + (i ==  listPath.Count - 1 ? "" : "/");
        }
        return path;
    }

    /// <summary>
    /// 将信息写入到桌面指定文件
    /// </summary>
    /// <param name="_str"></param>
    /// <returns></returns>
    private static void WriteMcImagePath(string _str)
    {
        var path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/McImagePath.txt";
        FileStream fs = null;
        StreamWriter sw = null;
        //创建文本
        if (!File.Exists(path))
        {
            fs = new FileStream(path,FileMode.Create,FileAccess.ReadWrite);
            sw = new StreamWriter(fs);
        }
        else
        {
            fs = new FileStream(path, FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
        }

        sw.WriteLine(_str);
        
        sw.Flush();
        sw.Close();
        fs.Close();
    }

补充注意事项:               

        在对资源进行编辑时候需要注意UGUI是继承了Graphic,继承了Graphic的UI被其他UI引用后没使用编辑器操作会导致该引用丢失,所以我们需要在编辑的时候加一步操作(记住UI的引用,编辑完成后还原)

        

    private class ComponentSetImageInfo
    {
        public FieldInfo Fileld;
        public PropertyInfo Property;
        public Object Obj;
        public Image RefImage;
    }

    private static void createPrefabRefImageInof(GameObject go,List<ComponentSetImageInfo> infos){
        foreach (var component in go.transform.GetComponentsInChildren<Component>(true))
        {   
            var filelds = component.GetType()
                .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            filelds = filelds.Where((o) => o.FieldType == typeof(Image) ||(o.FieldType == typeof(Graphic) && o.GetValue(component) is Image)).ToArray();
            foreach (var fileld in filelds)
            {
                var image = fileld.GetValue(component) as Image;
                if (image != null)
                {
                    infos.Add(new ComponentSetImageInfo()
                        {Fileld = fileld, Obj = component, RefImage = image});
                }
                //Debug.LogError(fileld.Name + fileld.FieldType.FullName);
                //fileld.SetValue(component,);
            }
            
            var propertys = component.GetType()
                .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            propertys = propertys.Where((o) => (o.PropertyType == typeof(Image)) || (o.PropertyType == typeof(Graphic) && o.GetValue(component) is Image)).ToArray();
            foreach (var property in propertys)
            {
                var image = property.GetValue(component) as Image;
                if (image != null)
                {
                    infos.Add(new ComponentSetImageInfo()
                        {Property = property, Obj = component, RefImage = image});
                }
            }
        }
    }

具体用法:

        

[MenuItem("UnityTools/GetComponentTools/替换Image为McImage")]
    static void CheckImageFolder()
    {
        string guid = Selection.assetGUIDs[0];
        var selectPath = AssetDatabase.GUIDToAssetPath(guid);
        List<string> dirs = new List<string>();
        GetDirsImage(selectPath, ref dirs);
    }
    
    //参数1 为要查找的总路径, 参数2 保存路径
    private static void GetDirsImage(string dirPath, ref List<string> dirs)
    {
        List<ComponentSetImageInfo> infos = new List<ComponentSetImageInfo>();
        foreach (string path in Directory.GetFiles(dirPath))
        {
            // Debug.Log(path);
            //获取所有文件夹中包含后缀为 .prefab 的路径
            if (System.IO.Path.GetExtension(path) == ".prefab" && path.IndexOf(@"UI\Slots") == -1)
            {
                dirs.Add(path.Substring(path.IndexOf("Asset")));
                string final_path = path.Substring(path.IndexOf("Asset")).Replace(@"\", "/");
                GameObject prefab = AssetDatabase.LoadAssetAtPath(final_path, typeof(System.Object)) as GameObject;

                var instance = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                createPrefabRefImageInof(instance,infos);
                foreach(Image child in instance.GetComponentsInChildren<Image>(true))
                {
                    UpdateImageByMcImage(child,infos);
                }
                PrefabUtility.ApplyPrefabInstance(instance, InteractionMode.UserAction);
                GameObject.DestroyImmediate(instance);
            }
        }         
        if (Directory.GetDirectories(dirPath).Length > 0)  //遍历所有文件夹
        {
            foreach (string path in Directory.GetDirectories(dirPath))
            {
                GetDirsImage(path, ref dirs);
            }
        }
    }

    static void UpdateImageByMcImage(Image image, List<ComponentSetImageInfo> refsObjs)
    {
        var targets = image.transform;

        var fillMethod = Image.FillMethod.Radial90;
        var fillOrigin = 1;
        var fillAmount = 0.0f;
        var clockwise = true;
        if (image.type == Image.Type.Filled)
        {
            fillMethod = image.fillMethod;
            fillOrigin = image.fillOrigin;
            fillAmount = image.fillAmount;
            clockwise = image.fillClockwise;
        }
        var enable = image.enabled;
        var spr = image.sprite;
        var color = image.color;
        var mat = image.material;
        var rayTarget = image.raycastTarget;
        var maskable = image.maskable;
        var type = image.type;
        
        //step1 找到所有引用自己的组件
        List<ComponentSetImageInfo> refSelfComponents = refsObjs.Where((o) => o.RefImage == image).ToList();

        DestroyImmediate(image,true);
        
        //Debug.LogError($"组件:{image},组件名:{targets.name}");
        var mcImage = targets.gameObject.AddComponent<MCImage>();
        mcImage.sprite = spr;
        //设置key
        string path = Application.streamingAssetsPath + "/rename.txt";
        string[] txt = File.ReadAllLines(path);
        Dictionary<string, string> keyDics = new Dictionary<string, string>();
        
        for (int i = 0; i < txt.Length; i++)
        {
            keyDics.Add(txt[i].Split(',')[0],txt[i].Split(',')[1]);
        }
        
        var assetPath = AssetDatabase.GetAssetPath(spr);
        
        if (!string.IsNullOrEmpty(assetPath))
        {
            var imageKey = "";
            if (keyDics.ContainsKey(assetPath))
            {
                foreach (var item in keyDics)
                {
                    if (assetPath == item.Key)
                    {
                        imageKey = item.Value;
                    }
                }
            }
            else
            {
                imageKey = spr.name;
            }
            
            //去除key带点的特殊符号
            if(imageKey.Contains('.'))
            {
                imageKey = imageKey.Replace('.','_');
            }
            
            string path1 = Application.streamingAssetsPath + "/rename1.txt";
            
            string[] txt1 = File.ReadAllLines(path1);
            
            Dictionary<string, string> keyDics1 = new Dictionary<string, string>();
        
            for (int i = 0; i < txt1.Length; i++)
            {
                keyDics1.Add(txt1[i].Split(',')[0],txt1[i].Split(',')[1]);
            }
            
            if (keyDics1.ContainsKey(imageKey))
            {
                foreach (var item in keyDics1)
                {
                    if (imageKey == item.Key)
                    {
                        imageKey = item.Value;
                    }
                }
            }
            
            //unity自带图片过滤
            if(!assetPath.Contains("Assets"))
            {
                imageKey = null;
            }

            mcImage.spriteKey = imageKey;
        }

        mcImage.enabled = enable;
        mcImage.color = color;
        mcImage.material = mat;
        mcImage.raycastTarget = rayTarget;
        mcImage.maskable = maskable;
        mcImage.type = type;
        if (mcImage.type == Image.Type.Filled)
        {
            mcImage.fillMethod = fillMethod;
            mcImage.fillOrigin = fillOrigin;
            mcImage.fillAmount = fillAmount;
            mcImage.fillClockwise = clockwise;
        }
        
        foreach (var refObj in refSelfComponents)
        {
            //Debug.LogError($"refobj:{refObj.Obj}");
            if(refObj.Fileld != null)
                refObj.Fileld.SetValue(refObj.Obj,mcImage);
            if (refObj.Property != null)
            {
                try
                {
                    refObj.Property.SetValue(refObj.Obj,mcImage);
                }
                catch (Exception e)
                {
                    
                }
            }
        }
    }

至此,unity编辑器对指定文件下所有prefab的操作完成。如有不懂,请留言。文章来源地址https://www.toymoban.com/news/detail-762966.html

到了这里,关于Unity Editor 遍历指定文件夹下的所有prefab的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • SHELL脚本 遍历文件夹下所有文件以及子文件夹

    SHELL脚本 遍历文件夹下所有文件以及子文件夹

    dir 要设置为局部变量 如果设置为全局变量 在func递归时传入的参数 会改变 dir的值,将导致之后的文件目录错误(为更改后的dir值) 当前目录情况: 执行完shell后: 附上代码: 如有不对,感谢指出。

    2024年02月12日
    浏览(14)
  • Node.js:实现遍历文件夹下所有文件

    Node.js:实现遍历文件夹 代码如下 参考文章 如何使用Node.js遍历文件夹详解

    2024年02月13日
    浏览(14)
  • java获取某个文件夹下的所有文件

    java获取某个文件夹下的所有文件

    目录 一.前言 二.获取文件夹下的文件路径 在我们平时编写开发文档的时候, 我们会获取到项目文件中的所有子文件来展示我们的源代码所储存的位置, 获取我们项目下的所有文件路径,  这时我们会如何用Java代码来获取我们项目下的所有文件呢, 今天我们来比编写一下代码 在

    2024年02月12日
    浏览(116)
  • linux 删除指定文件夹外的其他所有(文件)文件夹

    linux 删除指定文件夹外的其他所有(文件)文件夹

    方法一. 删除指定文件夹外的其他所有文件夹命令: 方法二. 删除指定文件夹外的其他所有文件夹命令: 查看当前文件夹下有哪些文件和子文件夹,当看到俩个文件夹和多个文件,需求是只保留 public 这个文件夹 其他的文件夹和文件 统统都删除,如下图所示,只要一个命令:

    2024年02月09日
    浏览(16)
  • java 在文件夹以及子文件夹中遍历获取指定文件的list

    1.  使用java 递归方法获取指定文件的list,相当于在一个文件夹以及子文件夹,搜索文件的功能。 直接上代码: 

    2024年02月13日
    浏览(15)
  • 【Python】获取指定目录下的文件夹和文件

    【Python】获取指定目录下的文件夹和文件

    我们经常会有对文件做批量处理的需求,获取指定目录下的文件夹和文件(有时需要获取所有文件,即子目录下的文件也需要获取)。Python 中扫描目录有两种方法: os.listdir() os.walk() 建立项目框架如下: 其中, test:项目文件夹名称,含有 aa子文件夹 和 main.py aa:文件夹,含

    2024年02月17日
    浏览(49)
  • 使用javaAPI对HDFS进行文件上传,下载,新建文件及文件夹删除,遍历所有文件

    目录 //通过工具类来操作hdfs   hdfs dfs -put d:user_info.txt  /user_info.txt  // 将文件放入到hdfs中  2.通过工具类来操作hdfs   hdfs dfs -get hdfs路径   本地路经  将文件放入到本地Windows中 3.通过工具类来操作hdfs   hdfs dfs -mkdir -p  hdfs路径 4.通过工具类来操作hdfs  查看一个文件是否存在

    2024年02月12日
    浏览(11)
  • java将指定目录下的文件复制到目标文件夹

    递归是一种基于函数调用自身的方法。它是一种非常常见的计算机编程技术,可以让程序员通过简单、优雅的方式来解决许多问题。 简单来说,递归是在函数执行过程中调用自身的过程。当函数被调用时,它会先执行函数体内的语句,然后再调用自己,这个过程将会重复执行

    2024年02月04日
    浏览(50)
  • [python]裁剪文件夹中所有pdf文档并按名称保存到指定的文件夹

    [python]裁剪文件夹中所有pdf文档并按名称保存到指定的文件夹

    最近在写论文的实验部分,由于latex需要pdf格式的文档,审稿专家需要对pdf图片进行裁剪放大,以保证图片质量。 原图: 裁剪后的图像: 代码粘贴如下。将input_folder和output_folder替换即可。(x1, y1), (x2, y2) 分别代表裁剪框的像素位置。

    2024年01月19日
    浏览(17)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包