存档这个需求拆开来说无非是两部分,存什么和怎么存。
存什么
以我的项目为例,我需要保存游戏对象的种类和坐标作为存档,用户读取存档时,再重新构建场景。
首先,我们需要一个存档类
public List<int> cubeListIndex = new List<int>();//方块的种类
public List<Vector3> cubeList = new List<Vector3>();//方块的坐标
然后我们需要一个方法来存储数据,就不具体写了,这不是重点。
怎么存
unity中比较常见存储方法有四类:PlayerPrefs,c#序列化,XML序列化,Json。
四种方法各有优劣,我使用的是c#序列化。
首先是存储数据
//创建文件并写入数据
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/Save1.save");
bf.Serialize(file, sl);
file.Close();
这里需要强调的一点是Application.persistentDataPath这个操作路径是PC端和移动端都可以使用的可读可写路径。
然后是读取数据
if (File.Exists(Application.persistentDataPath + "/Save1.save"))
{
//重置场景
// 读取数据
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/Save1.save", FileMode.Open);
SaveLoad sl = (SaveLoad)bf.Deserialize(file);
file.Close();
//加载场景
}
}
else
{
Debug.Log("No game Save1!");
}
File.Exists方法可以用来检查某个文件是否存在,重置场景和加载场景不表。