天天看点

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

目录

前言

一、官网地址

二、使用步骤

1.下载C#项目

2.打开C#项目

3.打开C#项目并生成项目需要的dll

 4,设置unity项目环境

5,将dll导入unity项目

6,下载编译文件

​7,编写批处理文件build.bat

8,编写protobuf文件Token.proto

9,双击build.bat生成C#文件

10,将C#文件导入unity项目

11,编写unity 测试代码

前言

Unity网络开发经常会使用到Protobuf协议

一、官网地址

https://github.com/protocolbuffers/protobuf

二、使用步骤

1.下载C#项目

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

https://github.com/protocolbuffers/protobuf/tree/master/csharp

2.打开C#项目

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

3.打开C#项目并生成项目需要的dll

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

 4,设置unity项目环境

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

5,将dll导入unity项目

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤
从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

6,下载编译文件

https://github.com/protocolbuffers/protobuf/releases

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤
7,编写批处理文件build.bat

@echo off

rmdir /s/q pb
rmdir /s/q CSharp

mkdir pb
mkdir CSharp

for /f "delims=" %%i in ('dir /b proto\*.proto') do (
	protoc --proto_path=proto --csharp_out=CSharp %%i
)

for /f "delims=" %%i in ('dir /b proto\*.proto') do (
	protoc --proto_path=proto --descriptor_set_out=pb/%%i %%i
)

echo 编译完成

pause
           

8,编写protobuf文件Token.proto

syntax = "proto3";

option csharp_namespace = "Net.Proto";

message Money{

  enum MoneyType{
    NULL = 0;
    gold = 1;
    gem = 2;
  }

  MoneyType type = 1;
  int32 num = 2;
}

message MoneyInfo{
  int32 msg_id = 8000;
  repeated Money moneyArr = 1;
  Money moneySingle = 2;
}

           

9,双击build.bat生成C#文件

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤
从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

10,将C#文件导入unity项目

从零开始Unity Google Protobuf 实战前言一、官网地址二、使用步骤

11,编写unity 测试代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Net.Proto;
using Google.Protobuf;

public class TestProtobuf : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        MoneyInfo ori = new MoneyInfo();

        ori.MsgId = 10000;

        Money temp= new Money();
        temp = new Money();
        temp.Num = 100;
        temp.Type = Money.Types.MoneyType.Gem;

        ori.MoneySingle = temp;
        ori.MoneyArr.Add(temp);

        //编码
        byte[] oriArr = ori.ToByteArray();
        //解码
        MoneyInfo message = MoneyInfo.Parser.ParseFrom(oriArr);

        Debug.Log(message);
        Debug.Log(message.MsgId);
        Debug.Log(message.MoneySingle);
        Debug.Log(message.MoneyArr);

    }

}
           

总结

恭喜你,从零完成了 protobuf环境搭建

继续阅读