Protobuf在Unity中的应用
发表于2018-03-21
Protobuf是一种数据交换格式,由于它是一种二进制的格式,比使用xml 进行数据交换快许多,可以把它用于分布式应用之间的数据通信或者异构环境下的数据交换作为一种效率和兼容性都很优秀的二进制数据传输格式,可以用于诸如网络传输、配置文件、数据存储等诸多领域。而下面要和大家介绍的就是Protobuf在Unity中的应用,一起来看看吧。


开发工具:VS、Unity
Protobuf官网
【VS项目】
使用VS新建一个C#空项目
右键点击引用

选择NuGet程序包->搜索Protobuf(这里我选择protobuf-net.Enyim)

点击下载安装后创建一
Person.cs对象来实战一个序列化和反序列话的应用程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtoBuf; namespace ProtobufObj { [ProtoContract] class Person { [ProtoMember(1)] public int id { get; set; } [ProtoMember(2)] public string name { get; set; } [ProtoMember(3)] public string address { get; set; } } }
接下来实现序列化与反序列化的函数
封装了两中函数接口,分别是转化为字符串与文件
新建ProtobufHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtoBuf; using System.IO; namespace ProtobufObj { class ProtobufHelper { //将对象序列化为字符串 public static string SerializerToString<T>(T t) { using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize(ms,t); return ASCIIEncoding.UTF8.GetString(ms.ToArray()); } } //将对象序列化到文件 public static void SerializerToFile<T>(T t,string filePath) { using (var file = File.Create(filePath)) { Serializer.Serialize(file,t); } } //将字符串转化为对象 public static T DederializerFromString<T>(string str) { //using作为语句,用于定义一个范围,在此范围的末尾将释放对象 //将字符串转化为内存流 using (MemoryStream ms=new MemoryStream(ASCIIEncoding.UTF8.GetBytes(str))) { T obj = Serializer.Deserialize<T>(ms); return obj; } } //将文件数据转化为对象 public static T DederializerFromFile<T>(string filePath) { using (var file = File.OpenRead(filePath)) { T obj = Serializer.Deserialize<T>(file); return obj; } } } }
最后测试下
新建Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ProtoBuf; namespace ProtobufObj { class Program { public static void Main(string[] args) { Person person = new Person { id=1, name="即步", address="江西赣州" }; //序列化 string str=ProtobufHelper.SerializerToString<Person>(person); //反序列化 Person obj=ProtobufHelper.DederializerFromString<Person>(str); } } }
调试程序,发现一起正常,Person对象被序列化为二进制字符串
当然也可以转化到文件
【Unity】
在VS项目后,我们在项目的Debug文件目录下可以找到protobuf-net.dll
在unity中新建一个名为Plugins文件,将protobuf-net.dll拷贝到其中
将Person.cs、Program.cs、ProtobufHelper.cs拷贝到unity中
修改Program.cs文件目录为:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ProtoBuf; using UnityEngine; namespace ProtobufObj { class Program : MonoBehaviour { void Start() { Person person = new Person { id=1, name="即步", address="江西赣州" }; //序列化 string str=ProtobufHelper.SerializerToString<Person>(person); Debug.Log(str); //反序列化 Person obj=ProtobufHelper.DederializerFromString<Person>(str); } } }
运行程序,一些正常。
资源提供:https://download.csdn.net/download/qq_33747722/9732131
来自:http://blog.csdn.net/qq_33747722/article/details/54236201