Untiy数据持久化(持续更新中。。。。)

8 篇文章 0 订阅

二进制保存方法

    /// <summary>
    /// 保存应用
    /// </summary>
    public  void SaveAPP()
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile" + "/byBin.txt");
        binaryFormatter.Serialize(fileStream, SaveData);
        fileStream.Close();

    }
    /// <summary>
    /// 读取已保存的APP
    /// </summary>
    public  void LoadAPP()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt",
                                                         FileMode.Open);
            SaveData = (SaveFormat)binaryFormatter.Deserialize(fileStream);
            fileStream.Close();
        }
        else
        {
            Debug.Log("文件不存在");
        }
    }

这里为读取和保存的方法,其中SaveData为自定义类且类需要序列化,读取的时候需要反序列化

Unity本身的数据持久化PlayerPrefs

   //保存数据
   PlayerPrefs.SetString("Name",mName);
   PlayerPrefs.SetInt("Age",mAge);
   PlayerPrefs.SetFloat("Grade",mGrade)
   //读取数据
   mName=PlayerPrefs.GetString("Name","DefaultValue");
   mAge=PlayerPrefs.GetInt("Age",0);
   mGrade=PlayerPrefs.GetFloat("Grade",0F);

适合保存数据量小的数据,且有两个特点:

       1、Unity3D中的数据持久化是以键值的形式存储的,可以看作是一个字典。

       2、Unity3D中值是通过键名来读取的,当值不存在时,返回默认值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值