代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class NewBehaviourScript : MonoBehaviour
{
//需要储存的数据
bool m_bool;
int m_int;
string m_string;
//创建用于存储的类,并在其中填入需要储存的数据
[System.Serializable]
public class Save
{
public bool s_bool;
public int s_int;
public string s_string;
}
//创建或覆盖存档
public void SaveGame()
{
//赋值想要储存的数据
m_bool = true;
m_int = 2;
m_string = "save ok";
//把要储存的数据写入创建的save
Save save = new Save();
save.s_bool = m_bool;
save.s_int = m_int;
save.s_string = m_string;
//设置储存路径并储存
string Save_Path = Application.persistentDataPath + "/Save.save";
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Save_Path);
bf.Serialize(file, save);
file.Close();
}
//读取存档
public void LoadGame()
{
//检测是否存在存档,若存在则读取存档
if (File.Exists(Application.persistentDataPath + "/Save.save"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/Save.save", FileMode.Open);
Save save = (Save)bf.Deserialize(file);
file.Close();
//将存档中的数据提取出来
m_bool = save.s_bool;
m_int = save.s_int;
m_string = save.s_string;
//结束,重启游戏进行测试
Debug.Log(save.s_bool + " " + m_bool);
Debug.Log(save.s_int + " " + m_int);
Debug.Log(save.s_string + " " + m_string);
}
}
}
//不明白为什么C#文本没有高亮
以上代码只是将一个类进行了储存,可以用于轻量存档。
windows存档的储存路径为:
C:\Users\username\AppData\LocalLow\company name\product name
链接:这里是一位作者总结的其他几种储存方法和路径