网上一搜会有很多介绍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
这个坑很深,我尝试了很多次又百度了很多最后才发现这个问题,你要是想读取和写入就得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读文本等