- 在Unity中使用Google.Protobuf
- 一、Google.Protobuf安装
- 二、示例
在Unity中使用Google.Protobuf
Google.Protobuf通过编译器protoc.exe对.proto文档进行编译,编译为C#格式的文件,进行序列化与反序列化。
编译指令:
protoc.exe --proto_path=./ xxx.proto --csharp_out=./
注意:protoc.exe 的路径需要添加至系统路径中。
一、Google.Protobuf安装
1、新建VS控制台项目。
2、选择项目,右键菜单选择“管理NuGet程序包”。
3、浏览 -> Google.Protobuf.Tools -> 安装。
安装后,在项目的同级目录会生成 packages文件夹。
此项packages/Google.Protobuf.Tools.3.6.1/tools/windows_x64/protoc.exe是Protobuf编译器,用于将.proto文件生成C#文件。
4、下载C#资源包,编译protobuf-3.6.1\csharp\src\Google.Protobuf生成Google.Protobuf.dll,并将Google.Protobuf.dll拷贝至Unity中。
二、示例
Person.proto文件:
syntax = "proto3";package shenjun;message Person{string name = 1;int32 id = 2;string email = 3;enum PhoneType{HOME = 0;MOBILE = 1;WORK = 2;}message PhoneNumber{string number = 1;PhoneType type = 2;}repeated PhoneNumber phone = 4;}
通过protoc.exe进行编译,生成Person.cs文件。
C#代码中使用Person类进行序列化及反序列化:
// 序列化Person p = new Person();p.Name = "shenjun";p.Id = 1;p.Email = "380921128@qq.com";p.Phone.Add(new Person.Types.PhoneNumber{Number = "12345678901",Type = Person.Types.PhoneType.Mobile});p.Phone.Add(new Person.Types.PhoneNumber{Number = "123456",Type = Person.Types.PhoneType.Home});// 转换成byte数组byte[] buff = p.ToByteArray();// 保存到文件using (var stream = File.Create("person.dat")){p.WriteTo(stream);}// 反序列化// 从byte数组反序列化IMessage IMperson = new Person();Person person = (Person)IMperson.Descriptor.Parser.ParseFrom(buff);// 从文件中反序列化using (var stream = File.OpenRead("person.dat")){Person pDes = Person.Parser.ParseFrom(stream);}
?
