開發環境
windows 7
Unity 5.3 及更高版本
前言
使用AssetDatabase.Load或AnimatorController.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; }
