您的位置:首页 > 移动开发 > Unity3D

Unity 二进制存储方法

2018-03-09 15:32 127 查看
在Manager类中

将文件存放在StreamingFile文件中

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[System.Serializable]
public struct Save
{

}

public void SaveGame()
{
saveByBin();
}

private void SaveByBin()
{
//序列化过程(将save转化为字节流)
//创建Save对象并保存当前游戏状态
Save save = CreateSaveGO();
//创建一个二进制格式化程序
BinaryFormatter bf = new BinaryFormatter();
//创建一个文件流
FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile" + "/byBin.txt");
//用二进制格式化程序的序列化方法来序列化Save对象,参数:创建的文件流和需要序列化的对象
bf.Serialize(fileStream,save);
//关闭流
fileStream.Close;

if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt")){
//若保存文件存在则执行
}
}

public void LoadGame()
{
LoadByBin();
}

private void LoadByBin()
{

if(!File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt")){
return;
}
//反序列化过程
//创建一个二进制格式化程序
BinaryFormatter bf = new BinaryFormatter();
//打开一个文件流
FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt",FileMode.Open);
//调用格式化程序的反序列化方法,将文件流转化为一个Save对象
Save save = (Save)bf.Deserialize(fileStream);
//关闭文件流
fileStream.Close;

SetGame(save);
}

private void SetGame(Save save)
{
foreach()
{
//清空原有数据
}
//重设数据
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unity3d
相关文章推荐