Unity 中实用方法的记录

这篇博客分享了在Unity中获取Assets目录同级目录的方法,如何使用EditorUtility的进程条,如何在编辑器菜单栏添加按钮。还讨论了路径处理,如全路径、绝对路径和斜杠转换,以及如何改变路径后缀。此外,还介绍了如何将日志打印到指定文件,使用计时器,获取资源引用,避免使用foreach造成的额外GC开销,以及使用CompareTag优化字符串比较。
摘要由CSDN通过智能技术生成

获取Assets文件夹同级的目录

我们要读取Assets目录同级的文件夹Assets.diff, 该文件夹的全路径可以这样获得:

//方法一
DirectoryInfo topDir = Directory.GetParent(Application.dataPath);
string diffFilePath = topDir.FullName + "/" + "Assets.diff";

//方法二
string diffFilePath = GetParentDirectory(Application.dataPath, 1) + "/" + "Assets.diff";

其中diffFilePath即为全路径

GetParentDirectory方法可以获得某路径的n级父目录

    public static string GetParentDirectory(string path, int parentCount)
    {
        int index = path.Length;
        while (parentCount > 0 && index > 0)
        {
            index = path.LastIndexOf('/', index - 1, StringComparison.Ordinal);
            --parentCount;
        }
        if (index < 0){
            return null;
        }
        return path.Substring(0, index);
    }

使用Editor进程条

当我们执行时间比较久的进程时(例如遍历Assets目录下所有FBX资源),可以使用EditorUtility 中的进度条来展示进程执行到哪一步了.

具体代码记录如下:

//展示进度条
EditorUtility.DisplayProgressBar("正在检查", "正在获取文件列表...", 0.0f);

var info = string.Format("{0}/{1}", tempCount, allCount);
EditorUtility.DisplayProgressBar("正在检查", "已检查" + info, (float)tempCount / allCount);

//最后一定要记得清理掉进度条, 不然它就一直留在界面上啦
EditorUtility.ClearProgressBar();

在编辑器的MenuBar添加按钮


                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值