关于 unity 中序列化文件移动端的存储和读取

网上一搜会有很多介绍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读文本等

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值