Unity常用数据持久化方式

1.引擎中PlayerPrefs保存


//保存
            PlayerPrefs.SetString("Name", "Joy");
            PlayerPrefs.SetInt("Age", 24);
            PlayerPrefs.SetFloat("Height", 167.7f);

//读取
  Name = PlayerPrefs.GetString("Name") ; 
  Age  = PlayerPrefs.GetInt("Age"); 
  Height = PlayerPrefs.GetFloat("Height");

//删除所有记录
PlayerPrefs.DeleteAll();
//删除某条记录
PlayerPrefs.DeleteKey("Age");
//将记录写入磁盘
PlayerPrefs.Save()

2.FileStream 文件读写

跳转另一篇文章

3.序列化为Json文件

Unity 自带Json序列化插件 JsonUtility [不支持List等]
》比较好用的Json序列化插件NewtonSoft ,注意使用的版本不能太高,Unity无法支持

NewtonSoft

4.XmlSerializer进行串行化

//定义案例类
  public class Entity
{
    public Entity()
    {
    }
    public Entity(string c, string f)
    {
      name = c;
      school = f;
    }
    public string name;
    public string school;
}
//读取数据
  public void Read()
  {
    List<Entity> entityList=null;
    XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
    using (StreamReader sr = new StreamReader(configPath))
    {  
       entityList = xs.Deserialize(sr) as List<Entity>;
    }
  }

//保存数据
public void Save()
{
  List<Entity> entityList=null;
  XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
  using (StreamWriter sw = File.CreateText(configPath))
  {
    xs.Serialize(sw, entityList);
  }
}

参考Unity本地数据持久化

5.ScriptableObject的使用

继承ScriptableObject,生成.asset资产文件,数据可以保存到Assets目录下,不依附于GameObject存在

【数据持久化目录】

参考Unity3D 数据持久化技术(一) - 知乎 (zhihu.com)

dataPath [只读]

streamingAssets [只读]

PersistentDataPath读写


image.png

Unity 使用Application.persistentDataPath进行存档_BIG_KENG的博客-CSDN博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容