Unity的AssetDatabase路径格式

开发环境

windows 7

Unity 5.3 及更高版本

 

前言

使用AssetDatabase.LoadAnimatorController.CreateAnimatorControllerAtPath等Unity内置Editor API进行文件操作时,经常碰到加载资源为null,或报路径不存在!

经过断点调试,发现绝大部分错误都是因为路径的分隔符存在两种:"/"和"\"。

我们使用 System.IO.Path 这个API得到的路径,其实也是以"\"分隔路径的。

我们在windows下打开资源管理器,某个目录或文件的路径为:e:\Code\GameFramework\ 或 \\192.168.80.100\XXX\

 

但是使用Unity的API,打印Application.dataPath 时,打印出:E:/xxx/client/trunk/Project/Assets,所以可知,它的路径和windows是反的,所以当我们使用的路径不符合Unity的规范时,经常会报资源加载失败。

比如某个FBX的路径为:Assets/Art/Characters/Wing/fbx_3005/3005@stand.FBX ,而如果你的输入的路径或拼接的路径不符合规范,那么极有可能会加载文件失败。

规范化路径

提供一个方法,把路径格式成Unity可读取的路径格式:

/// <summary>
    /// 格式化路径成Asset的标准格式
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string FormatAssetPath(string filePath)
    {
        var newFilePath1 = filePath.Replace("\\", "/");
        var newFilePath2 = newFilePath1.Replace("//", "/").Trim();
        newFilePath2 = newFilePath2.Replace("///", "/").Trim();
        newFilePath2 = newFilePath2.Replace("\\\\", "/").Trim();
        return newFilePath2;
    }
posted @ 2017-04-29 17:40  赵青青  阅读(4834)  评论(0编辑  收藏  举报