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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26916435/article/details/84136949

二进制保存方法

    /// <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中值是通过键名来读取的,当值不存在时,返回默认值

猜你喜欢

转载自blog.csdn.net/qq_26916435/article/details/84136949
今日推荐