網上一搜會有很多介紹unity各個路徑讀取方式。不盡相同,但是很少有介紹如何加載序列化文件bin文件的。因爲我這裏吧配置文件讀取後存儲爲bin文件放到streamingassets下,一塊打包,在pc端直接讀取即可,沒什麼可說的,但是到移動端,讀取方式等導致無法直接讀取,我採用的是copy到永久路徑下,這樣只需要在包體運行的時候copy一下即可。之後就可以直接讀取。
首先是對於移動端的copy操作:
string tablePath = Application.streamingAssetsPath + "/SerilizedFiles/";//源地址
#if UNITY_ANDROID && !UNITY_EDITOR //拷貝
string folderPath = Application.persistentDataPath+ "/SerilizedFile/";//移動地址
if (!Directory.Exists(folderPath))
{
//創建文件夾
Directory.CreateDirectory(folderPath);
}
Debug.Log("開始拷貝");
string frompath = tablePath + filesname;
string topath = folderPath + filesname;
//移動端先將文件copy到外部路徑
Debug.Log("源路徑" + frompath);
if (!File.Exists(topath))
{
Debug.Log("目標路徑" + topath);
using (WWW www = new WWW(frompath))
{
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log(www.error);
}
else
{
Debug.Log("數據:" + www.bytes.Length);
File.WriteAllBytes(topath, www.bytes);
}
}
} else
{
Debug.Log("已經copy:" + topath );
}
}
#endif
1,如果說你只想讀取streamingassets下的那該路徑要加上@"file:///" ,而你如果讀取persistentDataPath下的是不能加file的,直接使用的
2,如果你是想加載後在使用或者獲取數據,要加file的,而你使用file讀取是不能加的
這個坑很深,我嘗試了很多次又百度了很多最後才發現這個問題,你要是想讀取和寫入就得copy到persistentDataPath下,讀取記得不能加file,
接下來是讀取的操作:
string filepath =folderPath + filesnames[i];
Debug.Log("文件讀取路徑:" + filepath);
if (!File .Exists (filepath))
{
Debug.Log("讀取文件失敗:");
continue;
}
FileStream fs = new FileStream(filepath, FileMode.Open);
try
{
BinaryFormatter binayFormat = new BinaryFormatter();
string name = filesnames[i];
//fs.Dispose();
fs.Close();
}
catch (Exception ex)
{
Debug.Log("讀取失敗:" + ex);
fs.Close();
File.Delete(filepath);
}
這裏也是對應移動端的,讀取到數據後的操作沒有放。這裏讀的是bin文件,如果是其他文件,原來一樣的,也可以使用file讀文本等