Unity 通信方案 - 使用 Google Protobuf 序列化数据

发布时间 2023-10-08 16:38:37作者: imXuan

1.下载和编译

1.1 下载ProtoBuf源文件

  从 github 下载最新的 protoBuf 库,如下图所示 Releases · protocolbuffers/protobuf (github.com)

1.2 编译dll和导入

  解压后打开 /scharp/src 中的 sln 工程文件

   选择Release,Google.Protobuf,之后在生成中生成文件

  在以下路径中可以找到生成的所有文件 \csharp\src\Google.Protobuf\bin\Release\net45

  把所有文件都导入Plugins中,否则会报 Unable to resolve reference 'System.Runtime.CompilerServices.Unsafe'. Is the assembly missing or incompatible with the current platform? 这个错误

1.3 使用protoc编译成目标语言

  下载应用程序用于将proto文件编译成c#需要的文件

   编写一个proto格式的脚本,命名为 test.proto

// 指定版本
syntax = "proto3";
// C#中的命名空间(namespace)
package ProtoTest;
 
// 消息类
message MsgResult {
    // 消息码
    int32 code = 1;
    // repeated 相当于一个数组
    repeated int32 positions = 2;
}

  在该 exe 页面下打开一个 cmd 命令窗口,将 test.proto 编译成 csharp 的版本

protoc.exe --csharp_out=. test.proto

1.4 使用生成的脚本序列化和反序列化

  把csharp脚本导入到unity中,可以跟普通的序列化和反序列化一样使用