序列化: 将数据结构或对象转换成二进制串的过程。

反序列化:将在序列化过程中所生成的二进制串转换成数据结构或者对象的过程。

首先我们通过复制文件举例,这里面就包含序列化与反序列化的过程:

public class Test2 : MonoBehaviour
{
byte[] buffer;
private void Start()
{
//一次性复制 适用于比较小的文件,如文本文档等。
//序列化过程
using (FileStream stream = new FileStream(Application.dataPath + @"\Resources\123.txt", FileMode.Open, FileAccess.Read))
{
//创建一个 byte 类型数组,用来存储通过文件流读取的文件,数组的长度就是文件的长度。
buffer = new byte[stream.Length];
//将读取到的文件转为字节数组存入 buffer 数组中
stream.Read(buffer, , buffer.Length);
}
//反序列化过程
using (FileStream stream = new FileStream(Application.dataPath + @"\Floder1\123.txt", FileMode.Create, FileAccess.Write))
{
//将 buffer 数组中的字节转换回相应的格式,并写入相应文件中
stream.Write(buffer, , buffer.Length);
}
}
}
public class Test2 : MonoBehaviour
{
byte[] buffer;//声明一个字节数组
private void Start()
{
//分批量复制 适用于比较大的文件,如音频、视频等文件。
//定义每次读入的文件大小,10KB。
int maxSize = ;
//开启读入流
FileStream streamRead = new FileStream(Application.dataPath + @"\Resources\吴奇隆 - 转弯.mp3", FileMode.Open, FileAccess.Read);
//开启写入流
FileStream streamWrite = new FileStream(Application.dataPath + @"\Floder1\转弯.mp3", FileMode.Create, FileAccess.Write);
//实例化数组,长度为 maxSize。
buffer = new byte[maxSize];
//当前读取的字节数量
int num = ;
do
{
//读入文件
num = streamRead.Read(buffer, , maxSize);
//写入文件
streamWrite.Write(buffer, , num);
} while (num > );
//释放流
streamWrite.Dispose();
streamRead.Dispose();
}
}

下面这个例子是做了一个 Cube 的预制体,然后场景中放一个预制体,通过存档将 Cube 的信息序列化存入硬盘中,通过读档再将 Cube 的信息反序列化出来,生成在场景中,一般用于游戏存档功能。

Unity3D中大部分类(例如:Vector3)是不能被序列化的,所以这个时候我们需要使用  IFormatter  类,并自己写出一些可以序列化的类(例如下面代码中的:Info 和 VectorX 这个两个类就是我自己写的可以用来序列化的类)来替代这些类,从而实现序列化。这里写这个只是想让大家明白序列化的原理。一般来说,我们都会使用 JsonUtility 类来实现游戏的存档功能,非常简单,在下面的代码方法二中有举例。我们也可以使用  LitJson  插件来实现,用法与  JsonUtility  大同小异,网上有很多教程,这里就不多说了。

 using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System; public class Test1 : MonoBehaviour {
public GameObject cube;
void OnGUI()
{
if (GUILayout.Button("存档"))
{
cube = GameObject.Find("Cube");
if (cube != null)
{
Color c = cube.GetComponent<MeshRenderer>().material.color;
Info info = new Info(cube.transform.position, c.r, c.g, c.b, c.a);
//方法一:
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(Application.dataPath + "/info.obj", FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, info);
stream.Close(); //方法二:
//string str = JsonUtility.ToJson(info);
//File.WriteAllText(Application.dataPath + "/info.txt", str);
}
else
{
throw new Exception("物体不存在!");
}
}
if (GUILayout.Button("读档"))
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
IFormatter formatter = new BinaryFormatter();
//方法一:
Stream stream = new FileStream(Application.dataPath + "/info.obj", FileMode.Open, FileAccess.Read);
Info info = (Info)formatter.Deserialize(stream);
go.transform.position = info.pos;
go.GetComponent<MeshRenderer>().material.color = new Color(info.r, info.g, info.b, info.a);
stream.Dispose(); //方法二:
//string str = File.ReadAllText(Application.dataPath + "/info.txt");
//Info info = JsonUtility.FromJson<Info>(str);
//go.transform.position = info.pos;
//go.GetComponent<MeshRenderer>().material.color = new Color(info.r, info.g, info.b, info.a);
}
}
}
//在类的上面加上这个标签,这个类才能被序列化,需要注意。
[System.Serializable]
public class Info
{
public VectorX pos;
public float r;
public float g;
public float b;
public float a; public Info(VectorX pos,float r,float g,float b,float a)
{
this.pos = pos;
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
}

最新文章

  1. ASP.NET 在 Windows Azure 环境中使用基于 SQLServer 的 Session
  2. CodeForces336 A &amp; B
  3. 打开网页自动弹出QQ对话框的实现办法
  4. arcgis android 通过getExtent得到当前地图范围四个点的坐标
  5. c语言学习上的思考与心得
  6. java整合spring和hadoop HDFS
  7. Response.Cookies 和 Request.Cookies
  8. HDU 2035 人见人爱A^B 分类: ACM 2015-06-22 23:54 9人阅读 评论(0) 收藏
  9. 发现可高速缓存的 SSL 页面
  10. [AngularJS] Transclude -- using what existing in DOM to replace the template elements in directive
  11. iOS开发之字典数据建立模型步骤
  12. HDU 5700 区间交(线段树)
  13. iOS8推送消息的回复处理速度
  14. javase基础回顾(四) 自定义注解与反射
  15. ES语法注意事项
  16. 使用stackOfIntegers实现降序素数
  17. Spring核心--IOC
  18. Java虚拟机监控命令
  19. Java实现三大简单排序算法
  20. 解决org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named &#39;cacheManager&#39; is defined

热门文章

  1. Hibernate一对多OnetoMany
  2. node和npm的安装和镜像源的修改
  3. django之 基于queryset和双下划线的跨表查询
  4. [持续交付实践] pipeline使用:项目样例
  5. 基于LNMP的Zabbix4.0.1部署
  6. 《算法导论》——计数排序Counting Sort
  7. windows共享文件夹权限设置
  8. leetcode64
  9. setDaemon 守护线程
  10. python 爬虫启航2.0