从零开始Unity Google Protobuf 实战

4 篇文章 0 订阅

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

 


前言

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

一、官网地址

https://github.com/protocolbuffers/protobuf

二、使用步骤

1.下载C#项目

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

2.打开C#项目

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

 4,设置unity项目环境

5,将dll导入unity项目

 

6,下载编译文件

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


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#文件

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

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环境搭建

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值