1.普通类型
主要是这个路径:Application.persistentDataPath
下的文件,在更新时不会删除。
public class TestSave : MonoBehaviour
{
string path;
//创建文件夹
void Start()
{
path = Application.persistentDataPath + "save.txt";
FileInfo file1 = new FileInfo(path);
StreamWriter sw;
if (!file1.Exists) {
sw = file1.CreateText();
sw.Dispose();
}
}
//储存
public void save() {
string sa = "这是需要存档的信息";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(sa);
sw.Dispose();
}
public Text text;
//读取
public void load()
{
string nexline;
StreamReader sr = new StreamReader(path);
while ((nexline = sr.ReadLine()) != null) {
text.text = nexline;
}
}
}
2.序列化
序列化直接储存为2进制的数,所以可以存储任何格式的文件拓展名!! 也会对数据进行初级加密,让程序不这么易改 存储和读取也比较简单
将一个实体类整个作为序列化的数组
实体类前缀
[System.Serializable]
[System.Serializable]
public class PlayerData
{
public string name;
public int score;
}
读取和存储都要用到内置的一个工厂,直接调用就行了
调用模块
using System.Runtime.Serialization.Formatters.Binary;
public class Save : MonoBehaviour
{
public SavePlayerData savePlayerData;
string path;
public void Awake()
{
path = Application.persistentDataPath + "savewlwzalone.dat";
load();
}
public void save(int a) {
savePlayerData.Charper1_Pass = a;
FileStream fs = new FileStream(path,FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
//二进制数组工厂
bf.Serialize(fs,savePlayerData);
fs.Close();
}
public void load()
{
if (File.Exists(path)) {
FileStream fs = new FileStream(path,FileMode.Open);
BinaryFormatter binary = new BinaryFormatter();
savePlayerData=(SavePlayerData)binary.Deserialize(fs);
fs.Close();
}
else
{
savePlayerData = new SavePlayerData();
savePlayerData.Charper1_Pass = 1;
}
}
和前两部一块用的哈
3.JSon储存方式
用到插件
使用方法
储存转Json
JsonMapper.ToJson(对象或集合)
string json= JsonMapper.ToJson(scorelist[i]);
直接写出这个json就行了
sw.WriteLine(tojson);
读取
nextLine应该是代表的一行的json格式
JsonMapper.ToObject(nextLine)
scorelist.Add(JsonMapper.ToObject<ScoreEntity>(nextLine));
简单数据的存储;
直接用unity内置的就行了