一、protobuf3
首先应该想到的是看一下官方的支持, Protobuf。
Releases版下载地址
选择最新的 protobuf-csharp-x.x.x.tar.gz 或 protobuf-csharp-x.x.x.zip 压缩包。
解压,进入如下目录。
我需要其中的Google.Protobuf,
因为接下来由游戏项目所需的.proto文件生成的C#文件,将会使用到Google.Protobuf中定义的接口、类及方法。
将Google.Protobuf目录扔到unity(5.6.1f1)中,会出现一堆报错。
基本上都是如下三种。
Feature `interpolated strings' cannot be used because it is not part of the C# 4.0 language specification
Feature `expression bodied members' cannot be used because it is not part of the C# 4.0 language specification
Feature `null propagating operator' cannot be used because it is not part of the C# 4.0 language specification
从这里可以看出,Unity实际上只支持C#4.0以下的语法。而以上这些语法都是C#6.0的(Protobuf官方的目标是支持.Net4.5),有兴趣可以看看这几个语法。(另外Unity Editor只支持.Net3.5)
解决办法:
方法1.手动将以上报错处语法改成C# 4.0的。这会很蛋疼,有100多处,不推荐
方法2.将Google.Protobuf生成为支持.net3.5(对应C#3.0) 的.dll。
方法3.目前,unity(2018及以上)已支持.net 4.x Equivalent。在playersetting里设置即可。
方法2的解决步骤如下:
打开上面目录中的 Google.Protobuf.sln 工程(使用vs2017,安装时选择的Unity和.Net模块)。按如下图步骤生成Google.Protobuf.dll。
结果如下,拖入Unity,无错误。
现在,要将.proto文件导出成cs文件,还需要protoc.exe。
还是在这里下载 地址
选择 protoc-x.x.x-win32.zip (windows下)
解压bin目录下即可看到
写一个简单的.proto 文件 message.proto 和 简单的批处理文件 test.bat
运行,得到 Message.cs,放入Unity,就可以使用了。
void Start()
{
byte[] bytes;
SearchRequest t = new SearchRequest
{
Query = "";
PageNumber = 0;
ResultPerPage = 0;
}
using (MemoryStream stream = new MemoryStream())
{
t.WriteTo(stream);
bytes = stream.ToArray();
}
SearchRequest copy = SearchRequest.Parser.ParseFrom(bytes);
}
--------------------------------------------------NRatel割--------------------------------------------------
二、protobuf2
如果你的proto文件是syntax = "proto2"的,用上边的方式是不行的。
因为上边用protoc.exe生成C#文件,只支持 protobuf3。。
如果自己的游戏项目用的是protobuf2,
那应该使用 这个版本
可以放心用,因为已经被Google接管了。
这里也列举了两个版本的差别,如下:
这个版本用起来还是比较方便的。下载解压后进入build目录,执行BuildAll.bat
等待执行完毕,得到build_output/tools目录,进入并放入自己的.proto文件,同样写一个简单的test.bat,执行。 获得Message.cs。 将Google.ProtocolBuffers.dll、Google.ProtocolBuffers.Serialization.dll 和 Message.cs放入Unity即可使用。
--------------------------------------------------NRatel割--------------------------------------------------
三、在lua中使用( protobuf2 )
另外,目前很多unity项目使用lua开发, 而protobuf官方并没有对lua做支持。
如果想在lua中使用protobuf,可以这样干。
protobuf2实测没问题,protobuf3没试过。
1.Make and install protobuf.so ( or protobuf.dll in windows ) and protobuf.lua into your lua path.
lua53的如下:
2.将.proto文件生成 二进制文件
利用 protoc.exe执行,得到Message.bytes
protoc --descriptor_set_out=Message.bytes --include_imports Message.proto
3.将Message.bytes放在Resource下, 在Unity中加载注册
-- Load Protocol (Main中运行一次即可)
local asset = Resouces.Load("Message.bytes", TextAsset)
local pbData = asset.bytes
protobuf.register(pbData)
或 直接使用 protobuf.register_file("Message.bytes")也行
4.使用
protobuf.encode()
protobuf.decode()