目标:实现数据存储为二进制文件,然后通过二进制文件解析数据。
目标分为三个阶段:1、将数据结构转化为二进制(至于数据是怎样读取进来的这个就不说了,因为方式比较多,但是读取进来一定都会以特定的数据结构形式来保存)。2、加载二进制文本。3、加载为对应的数据结构。
阶段一:将数据结构转化为二进制有两种方式:1:利用C#的BinaryWrite,2:使用函数把数据转化成byte数组,然后在写入。
方法1:
public bool SaveBinaryFile(string _path, string _name, TextAsset t){
string content = t.text;
//二进制文件流信息
BinaryWriter bw = new BinaryWriter(new FileStream (_path + _name, FileMode.Create));;
FileStream fs = new FileStream (_path + _name, FileMode.Create);
try {
bw = new BinaryWriter(new FileStream (_path + _name, FileMode.Create));
}catch(IOException e){
Debug.Log (e.Message);
}
try {
bw.Write(content);
}catch(IOException e){
Debug.Log (e.Message);
}
debugInfo += "文件创建成功!\n";
return true;
}
说明:这种方法代码也没几行,方式也很好理解,我把过程封装成函数,传入路径和文件名即可(温馨提示:unity里面二进制存在StreamingAssets文件夹里面,若不懂可百度,有很多资源)。
为了让大家更好的理解我把路径贴出来: