不同于unity自带的PlayerPrefs的字典式存储,本文主要说明三种文件存储的具体实现方式(项目原型基于siki案例–存档与读档,类似于打砖块的小游戏),即:二进制方法、XML以及JSON。
三种存储方式的对比
一、二进制方式存储:
存储简单,但基本没有可读性。
二、XML:
可读性强,但文件庞大,冗余信息多。
三、JSON:
数据格式比较简单,易于读写,但是不直观,可读性比XML差。
三种方式存储的预先准备
首先得创建一个Save类存储相关数据并标记为可序列化,本例具体代码如下:
(新建一个C#脚本,将继承类删除即可开始编写Save类,Save类用于存储需要存储的数据)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Save
{
public List<int> activeMonsterPosition = new List<int>();
public List<int> activeMonsterType = new List<int>();
public int shootNum;
public int score;
}
一、二进制方式的存档与读档
需要添加两个命名空间:
1、using System.IO; //用于文件的读写
2、using System.Runtime.Serialization.Formatters.Binary; //用于创建二进制格式化程序
存档代码如下:
private void SaveByBin()
{
//创建存储类对象
Save save = CreateSaveGo();
//创建二进制格式化程序
BinaryFormatter binaryFormatter = new BinaryFormatter();
//创建文件流(create参数为存储路径,注意路径前的"/"以及标明文件名称和格式)
FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile" + "/byBin.txt");
//用二进制格式化程序的序列化方法来序列化save对象
binaryFormatter.Serialize(fileStream, save);
//关闭文件流
fileStream.Close();
}
读档代码如下:
private void LoadByBin()
{
if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt")) //检测是否存在读档信息
{
//创建二进制格式化程序
BinaryFormatter binaryFormatter = new BinaryFormatter();
//创建文件流打开读档信息
FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
//调用二进制格式化程序的反序列化方法,将文件流转化为Save对象
Save save = (Save)binaryFormatter.Deserialize(fileStream); //返回值为object类型,需要强制转换为需要的类型
//关闭文件流
fileStream