Unity Protobuf实践

Unity Protobuf实践 官方文档https://protobuf.com.cn/overview/1. 获取Protobuf下载源码并生成dllGitHub - protocolbuffers/protobuf: Protocol Buffers - Googles data interchange format解压选择csharpVS打开项目生成解决方案获取dll.net2.0只包含Protobuf.dll其他dll得从.net45获取导入Unity Plugins目录2. 使用protoc工具获取协议对应的.cs文件新建proto文件syntax proto3; package Proto; message Info { string nameValue1; int32 levelValue2; }使用protoc获取cscd C:\Users\59886\Desktop\SeeURP6\Tools\Proto\ protoc.exe --proto_path . protos/Info.proto --csharp_out./out/3. 在Unity使用cs序列化与反序列化工具public class ProtoTool { /// summary /// 序列化 /// /summary /// param namemessage/param /// returns/returns public static byte[] Serialize(IMessage message) { return message.ToByteArray(); } /// summary /// 反序列化 /// /summary /// typeparam nameT/typeparam /// param namepackct/param /// returns/returns public static T DeSerializeT(byte[] packct) where T : IMessage, new() { IMessage message new T(); try { return (T)message.Descriptor.Parser.ParseFrom(packct); } catch (System.Exception e) { throw e; } } }实例Info info new Info(); info.NameValue liu; info.LevelValue 1; byte[] data ProtoTool.Serialize(info); Info info2 ProtoTool.DeSerializeInfo(data); Debug.LogError($nameValue {info2.NameValue}, levelValue {info2.LevelValue});反序列化时可从协议生成的类中获取Parser参考在Unity中使用Protobuf进行序列化_unity c# proto buffer-CSDN博客