unity 中 protobuff 的用法 一句话攻略


(一)unity 添加 pb 的 dll 支持。
1,从GitHub上下载protobuf源码 (源码链接:https://github.com/google/protobuf),找到 csharp 分支检出。

2,用 VisualStudio 打开工程目录下 csharp/src/Google.Protobuf.sln 文件。

3,ctrl+k,生成 DLL 文件。

4,把 bin 下面生成的 Google.Protobuf.dll 复制到 unity 中。Done!

 


 

 (二)生成 .proto 对应的 .cs 文件。

1,在 GayHub 上下载 proto文件的编译器(Git地址: https://github.com/google/protobuf/releases),下载对应的平台的编译器(如我是mac 下载的 protoc-3.6.1-osx-x86_64)

2,写一个 TestProto3.proto 文件

------------------------------------
  syntax = "proto3"; // 必须,标明 proto 语法的版本
  package TestProto3; // 生成的 cs 的命名空间

  message PersonMc{
    string Name = 1; // 123 不是参数默认值,是参数标签,从上往下写就行,不用管啥意思
    int32 Age = 2;
    repeated string Hobbies = 3; // repeated 表示数组
  }
  // proto 的更多语法可以参考 https://developers.google.com/protocol-buffers/docs/proto3
------------------------------------

3,打开刚才的编译器目录,运行 bin 下面的 protoc 程序。执行命令(我这个是mac 其他的自己查找)
------------------------------------
  protoc ./TestProto3.proto --csharp_out=./
------------------------------------

4,上一步编译成功,获得一个 TestProto3.cs 文件。

5,把这个 cs 复制到 unity 中。 Done!

 


 

 (三)使用 protobuff的序列化和反序列化

------------------------------------
举个🌰
  using UnityEngine;
  using TestProto3; // (第二步中的 proto 的 package)
  using Google.Protobuf; // (第一步的 dll)

  public class TestMc : MonoBehaviour
  {
    void Start()
    {
      // 新建一个 PersonMc 对象
      PersonMc person1 = new PersonMc();
      person1.Name = "XiaoMa";
      person1.Age = 18;
      person1.Hobbies.Add("吃饭");
      person1.Hobbies.Add("睡觉");
      // 对象转字节数组 -- 传给后端
      byte[] databytes = person1.ToByteArray();

      // 字节数据还原成对象
      IMessage imPerson = new PersonMc();
      PersonMc personDe = new PersonMc();
      personDe = (PersonMc)imPerson.Descriptor.Parser.ParseFrom(databytes);

      // 输出结果
      UnityEngine.Debug.Log(personDe.Name);
      UnityEngine.Debug.Log(personDe.Age);
      UnityEngine.Debug.Log(personDe.Hobbies[0]);
      UnityEngine.Debug.Log(personDe.Hobbies[1]);
    }
  }
------------------------------------

 

打完收工~

posted on 2016-09-13 16:31  Sweet小马  阅读(821)  评论(0编辑  收藏  举报

导航