下面介绍几种 Unity本地记录存储的实现方式。

第一种 Unity自身提供的 PlayerPrefs

//保存数据


  1. PlayerPrefs.SetString("Name",mName);
  2. PlayerPrefs.SetInt("Age",mAge);
  3. PlayerPrefs.SetFloat("Grade",mGrade)

//读取数据


  1. mName=PlayerPrefs.GetString("Name","DefaultValue");
  2. mAge=PlayerPrefs.GetInt("Age",0);
  3. mGrade=PlayerPrefs.GetFloat("Grade",0F);

//清除所有记录

 PlayerPrefs.DeleteAll();

//删除其中某一条记录

PlayerPrefs.DeleteKey("Age");

//将记录写入磁盘

PlayerPrefs.Save()

第二种 BinaryFormatter 二进制序列化

假设有一个Player类


  1. [System. Serializable]
  2. public class Player
  3. {
  4. public int health;
  5. public int power;
  6. public Vector3 position;
  7. }

由于BinaryFormatter序列化不支持Unity的Vector3类型,所以我们需要做一下包装。


  1. public class PlayerData{
  2. public int level;
  3. public int health;
  4. public float[] position;
  5. public PlayerData(Player player)
  6. {
  7. this.level = player.level;
  8. this.health = player.health;
  9. this.position = new float[3];
  10. this.position[0] = player.transform.position.x;
  11. this.position[1] = player.transform.position.y;
  12. this.position[2] = player.transform.position.z;
  13. }
  14. }

我们对PlayerData进行保存和读取。读取出来的PlayerData可以赋给Player。


  1. public static class SaveSystem{
  2. //保存数据
  3. public static void SavePlayer(Player player)
  4. {
  5. BinaryFormatter formatter = new BinaryFormatter();
  6. string path = Application.persistentDataPath+"/player.fun";
  7. FileStream stream = new FileStream(path,FileMode.Create);
  8. PlayerData data = new PlayerData(player);
  9. formatter.Serialize(stream,data);
  10. stream.Close();
  11. }
  12. //读取数据
  13. public static PlayerData LoadPlayer()
  14. {
  15. string path = Application.persistentDataPath+"/player.fun";
  16. if(File.Exists(path))
  17. {
  18. BinaryFormatter formatter = new BinaryFormatter();
  19. FileStream stream = new FileStream(path,FileMode.Open);
  20. PlayerData data = formatter.Deserialize(stream) as PlayerData;
  21. stream.Close();
  22. return data;
  23. }else{
  24. Debug.LogError("Save file not found in "+path);
  25. return null;
  26. }
  27. }
  28. }

第三种 保存为json格式的文本文件

使用 Unity 自身API JsonUtility。

保存数据


  1. public static void SavePlayerJson(Player player)
  2. {
  3. string path = Application.persistentDataPath+"/player.json";
  4. var content = JsonUtility.ToJson(player,true);
  5. File.WriteAllText(path,content);
  6. }

读取数据


  1. public static PlayerData LoadPlayerJson()
  2. {
  3. string path = Application.persistentDataPath+"/player.json";
  4. if(File.Exists(path)){
  5. var content = File.ReadAllText(path);
  6. var playerData = JsonUtility.FromJson<PlayerData>(content);
  7. return playerData;
  8. }else{
  9. Debug.LogError("Save file not found in "+path);
  10. return null;
  11. }
  12. }

第四种 XmlSerializer进行串行化

假如有类


  1. public class Entity
  2. {
  3. public Entity()
  4. {
  5. }
  6. public Entity(string c, string f)
  7. {
  8. name = c;
  9. school = f;
  10. }
  11. public string name;
  12. public string school;
  13. }

读取数据


  1. List<Entity> entityList=null;
  2. XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
  3. using (StreamReader sr = new StreamReader(configPath))
  4. {
  5. entityList = xs.Deserialize(sr) as List<Entity>;
  6. }

保存数据


  1. List<Entity> entityList=null;
  2. XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
  3. using (StreamWriter sw = File.CreateText(configPath))
  4. {
  5. xs.Serialize(sw, entityList);
  6. }

对应的xml文件为:


  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ArrayOfEntity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  3. <Entity>
  4. <Name>Alice</Name>
  5. <School>SJTU</School>
  6. </Entity>
  7. <Entity>
  8. <Name>Cici</Name>
  9. <School>CSU</School>
  10. </Entity>
  11. <Entity>
  12. <Name>Zero</Name>
  13. <School>HIT</School>
  14. </Entity>
  15. </ArrayOfEntity>

Unity3D 本地数据持久化几种方式的更多相关文章

  1. ios网络学习------4 UIWebView的加载本地数据的三种方式

    ios网络学习------4 UIWebView的加载本地数据的三种方式 分类: IOS2014-06-27 12:56 959人阅读 评论(0) 收藏 举报 UIWebView是IOS内置的浏览器, ...

  2. iOS --- UIWebView的加载本地数据的三种方式

    UIWebView是IOS内置的浏览器,可以浏览网页,打开文档  html/htm  pdf   docx  txt等格式的文件.  safari浏览器就是通过UIWebView做的. 服务器将MIM ...

  3. Linux就这个范儿 第15章 七种武器 linux 同步IO: sync、fsync与fdatasync Linux中的内存大页面huge page/large page David Cutler Linux读写内存数据的三种方式

    Linux就这个范儿 第15章 七种武器  linux 同步IO: sync.fsync与fdatasync   Linux中的内存大页面huge page/large page  David Cut ...

  4. python爬虫---爬虫的数据解析的流程和解析数据的几种方式

    python爬虫---爬虫的数据解析的流程和解析数据的几种方式 一丶爬虫数据解析 概念:将一整张页面中的局部数据进行提取/解析 作用:用来实现聚焦爬虫的吧 实现方式: 正则 (针对字符串) bs4 x ...

  5. Solr 删除数据的几种方式

    原文出处:http://blog.chenlb.com/2010/03/solr-delete-data.html 有时候需要删除 Solr 中的数据(特别是不重做索引的系统中,在重做索引期间).删除 ...

  6. SparkStreaming获取kafka数据的两种方式:Receiver与Direct

    简介: Spark-Streaming获取kafka数据的两种方式-Receiver与Direct的方式,可以简单理解成: Receiver方式是通过zookeeper来连接kafka队列, Dire ...

  7. SparkStreaming与Kafka,SparkStreaming接收Kafka数据的两种方式

    SparkStreaming接收Kafka数据的两种方式 SparkStreaming接收数据原理 一.SparkStreaming + Kafka Receiver模式 二.SparkStreami ...

  8. 【代码笔记】iOS-向服务器传JSON数据的两种方式

    一,代码. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. ...

  9. .NET MVC控制器向视图传递数据的四种方式

    .NET MVC控制器向视图传递数据的四种方式: 1.ViewBag  ViewBag.Mvc="mvc"; 2.ViewData ViewBag["Mvc"] ...

随机推荐

  1. 从零搭建springboot服务03-redis消息订阅

    愿历尽千帆,归来仍是少年 1.所需依赖 <!-- Redis依赖 --> <dependency> <groupId>org.springframework.boo ...

  2. [bug] ORACLE not available

    参考 https://www.cnblogs.com/sank/p/10046277.html

  3. [Qt] 事件机制(四)

    滚轮事件:滚动滚轮实现窗口大小缩放 widget.h中增加: protected: void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; void ...

  4. sed常用

    行首添加字符串 # cat a [root@localhost b]# vim a 文件a将每行的第1列添加HEAD [root@localhost b]# sed 's/^/HEAD &/g ...

  5. Linux_配置加密的https

    一.配置https 1.安装好httpd服务后,安装mod_ssl模块 //首先查看是否安装mod_ssl [root@localhost ~]# rpm -qa | grep mod_ssl //安 ...

  6. 【遥感数字图像处理实验】Erdas版详细图文实验教程(8实验全)

    @ 目录 1. 专栏简介 2. 专栏地址 3. 专栏目录 1. 专栏简介 遥感数字图像的处理,是对遥感数字图像的计算机处理.与工业和医学数字图像不同,遥感数字图像类型更为多样,内容更为复杂.因此,遥感 ...

  7. MMF的初步介绍:一个规范化的视觉-语言多模态任务框架

    在VQA, Image Caption等任务中,构建模型是一件工作量较大的工作.有没有什么能减少这些重复的工作量呢?与此同时,Pytorch,tensorflow等开源的深度学习工具包发布,大大减少了 ...

  8. GO学习-(37) 使用Air实现Go程序实时热重载

    使用Air实现Go程序实时热重载 今天我们要介绍一个神器--Air能够实时监听项目的代码文件,在代码发生变更之后自动重新编译并执行,大大提高gin框架项目的开发效率. 为什么需要实时加载? 之前使用P ...

  9. NBU Rman异机恢复Oracle

    前段时间一个亿级分区表,被分割成历史表和业务表,历史表中保留15天以外的数据,每天都会从业务表中的15天外的数据copy到历史表,并删除业务表15天外的数据,逻辑也很简单,但插入历史表的where 条 ...

  10. Stopper的使用

    工具类,抽象死循环逻辑的 import java.util.concurrent.atomic.AtomicBoolean; /** * if the process closes, a signal ...