Unity简单的数据存储方式:序列化与反序列化

前言

我们知道要想制作一个游戏的话,数据的保存是很重要的。就我目前的学习,我觉得比较简单好用的就是利用序列化与反序列化进行数据存储,然后存储的文件可以是:一、txt文件,二、Json文件

注意事项

一、
要想序列化某个类,必须要在类的顶部声明[Serializable],表明他是需要序列化的。
二、
一般Vector和quaternion之类的数据类型是不可以序列化的,因为.Net本来就没有这种数据类型,所以没法序列化。那么如果我们要保存这类数据是怎么办呢?没关系,Unity已经帮我们搞定了,下面会说到。

使用txt文件存储

这种方式就是很简单的将对象序列化成2进制流,然后保存在txt文件中:

string path= Application.dataPath + "/StreamingFile/" + Name + ".txt";
            if(File.Exists(path))
            {
                File.Delete(path);
            }
            FileStream fileStream = File.Create(path);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(需要序列化的对象);
            fileStream.Close();
            AssetDatabase.Refresh();//刷新文件夹

需要使用的时候,再将txt文件中的2进制流反序列化为对象:

string path = Application.dataPath + "/StreamingFile/" + name + ".json";
        if (File.Exists(path))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = new FileStream(path, FileMode.Open);
            对象 = bf.Deserialize(fs) as 类名;//反序列化
            fs.Close();
        }

使用Json

我发现好多人都是使用ListJson插件去存储Json数据,但是这个插件我觉得并好用,因为它竟然不能解析float类型,更别说Vector3等常用的数据类型了。所以还是人家Unity自带的JsonUtility好用,可以存储Vector类型,简直不要太爽。使用的方式也超级简单,就是将对象转换为Json字符串(这个应该也是用了序列化),然后存储在Json文件里面:

string path=Application.dataPath+ "/StreamingFile/" + Name + ".json";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            string stringJson = JsonUtility.ToJson(需要存储的对象);
            StreamWriter sw = new StreamWriter(path);
            sw.Write(stringJson);
            sw.Close();
            AssetDatabase.Refresh();

读取也是一个样,将Json文件里面的字符串解析成对象就行了

string path = Application.dataPath + "/StreamingFile/" + name + ".json";
        if (File.Exists(path))
        {
            StreamReader sr = new StreamReader(path);
            string jsonStr = sr.ReadToEnd();
            对象 = JsonUtility.FromJson<类名>(jsonStr);
            sr.Close();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值