官方文档:https://protobuf.com.cn/overview/
1. 获取Protobuf:
下载源码并生成dll:
GitHub - protocolbuffers/protobuf: Protocol Buffers - Google's data interchange format
解压选择csharp:
VS打开项目:
生成解决方案:
获取dll:
(.net2.0只包含Protobuf.dll,其他dll得从.net45获取)
导入Unity Plugins目录:
2. 使用protoc工具获取协议对应的.cs文件:
新建proto文件:
syntax = "proto3"; package Proto; message Info { string nameValue=1; int32 levelValue=2; }使用protoc获取cs:
cd 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 name="message"></param> /// <returns></returns> public static byte[] Serialize(IMessage message) { return message.ToByteArray(); } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="packct"></param> /// <returns></returns> public static T DeSerialize<T>(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.DeSerialize<Info>(data); Debug.LogError($"nameValue = {info2.NameValue}, levelValue = {info2.LevelValue}");反序列化时,可从协议生成的类中获取Parser:
参考:在Unity中使用Protobuf进行序列化_unity c# proto buffer-CSDN博客