unity-doc-pb3

下载

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

编译dll

建议使用vs2019打开,不然好多异常问题。

  • 进入protobuf-3.11.2\csharp\src
  • 使用vs打开Google.Protobuf.sln
  • 右键Google.Protobuf,然后选择重新构建
  • 把编译好的dll都放到unity的Plugins目录
    • Google.Protobuf
    • System.Buffers
    • System.Memory
    • System.Runtime.CompilerServices.Unsafe

测试

  • test.proto 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
syntax = "proto3"; 					// (1)

package com.pack1; // (2)

enum StudentType // (3)
{
GOOD = 0;
BAD = 1;
}

message StudentInfo { // (4)
string name = 1; // (5)
repeated int32 socre = 2; // (6)
StudentType sType = 3;
}

message StudentInfoReq {
int32 sId = 1;
int32 opt = 2;
}

message StudentInfoRes {
int32 code = 1;
int32 sId = 2;
StudentInfo sInfo = 3;
}

message GameEndNoticeMsg {
int32 code = 1;
int32 sId = 2;
StudentInfo sInfo = 3;
}
  • c#测试文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using Com.Pack1;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Runtime.Serialization.Formatters.Binary;
using Google.Protobuf;
using System.IO;

public class Net_TestPb3 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

byte[] bytes;

StudentInfoReq sq = new StudentInfoReq();
sq.SId = 1;
sq.Opt = 2;

using (MemoryStream stream = new MemoryStream())
{
sq.WriteTo(stream);
bytes = stream.ToArray();
}

StudentInfoReq sq2 = StudentInfoReq.Parser.ParseFrom(bytes);

Debug.LogError(sq2.SId);
Debug.LogError(sq2.Opt);
}

}

报错解决

  • 当前 .NET SDK 不支持将 .NET Core 2.1 设置为目标。

登录微软官方下载对应的vs的sdkhttps://dotnet.microsoft.com/download/visual-studio-sdks?utm_source=getdotnetsdk&utm_medium=referral