unity各种存档方法

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内置的就行了

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值