Unity幾個重要路徑的差別
- 一、Resources(隻讀)
- 二、 StreamingAssets(隻讀)
- 三、 Application.dataPath(隻讀)
- 四、Application.persistentDataPath(可讀寫)
- 五、在unity代碼中進行檔案增删改查處理
一、Resources(隻讀)
• Resources檔案夾下的資源無論使用與否都會被打包
• 資源會被壓縮,轉化成二進制
• 打包後檔案夾下的資源隻讀
• 無法動态更改,無法做熱更新
• 使用Resources.Load加載
二、 StreamingAssets(隻讀)
• 流資料的緩存目錄
• 檔案夾下的資源無論使用與否都會被打包
• 資源不會被壓縮和加密
• 打包後檔案夾下的資源隻讀,主要存放二進制檔案
• 無法做熱更新
• WWW類加載(一般用CreateFromFile ,若資源是AssetBundle,依據其打包方式看是否是壓縮的來決定)
• 相對路徑,具體路徑依賴于實際平台
•Application.streamingAssetsPath
• IOS: Application.dataPath + “/Raw” 或Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data/Raw
static void WriteLine()
{
StreamWriter writer;
string filePath = "";
filePath = Application.streamingAssetsPath + "/BuildJson.json";
FileInfo fileInfo = new FileInfo(filePath);
writer = new StreamWriter(filePath, false);
writer.Write(JsonMapper.ToJson(buildJson));
// 釋放 流
writer.Close();
//writer.Flush();
}
三、 Application.dataPath(隻讀)
• 遊戲的資料檔案夾的路徑(例如在Editor中的Assets)
• 很少用到
• 無法做熱更新
• IOS路徑: Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data
四、Application.persistentDataPath(可讀寫)
• 持久化資料存儲目錄的路徑( 沙盒目錄,打包之前不存在 )
• 檔案夾下的資源無論使用與否都會被打包
• 運作時有效,可讀寫
• 無内容限制,從StreamingAsset中讀取二進制檔案或從AssetBundle讀取檔案來寫入PersistentDataPath中
• 适合熱更新
• IOS路徑: Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Documents
五、在unity代碼中進行檔案增删改查處理
/// <summary>
/// 拷貝檔案夾
/// </summary>
/// <param name="srcPath">需要被拷貝的檔案夾路徑</param>
/// <param name="tarPath">拷貝目标路徑</param>
private static void CopyFolder(string srcPath, string tarPath)
{
if (!Directory.Exists(srcPath))
{
Debug.Log("CopyFolder is null.");
return;
}
if (!Directory.Exists(tarPath))
{
Directory.CreateDirectory(tarPath);//建立檔案夾
}
//獲得源檔案下所有檔案
List<string> files = new List<string>(Directory.GetFiles(srcPath));
files.ForEach(f =>
{
string destFile = Path.Combine(tarPath, Path.GetFileName(f));
File.Copy(f, destFile, true); //覆寫模式
});
//獲得源檔案下所有目錄檔案
List<string> folders = new List<string>(Directory.GetDirectories(srcPath));
folders.ForEach(f =>
{
string destDir = Path.Combine(tarPath, Path.GetFileName(f));
CopyFolder(f, destDir); //遞歸實作子檔案夾拷貝
});
}