Unity Protobuf实践

官方文档:https://protobuf.com.cn/overview/

1. 获取Protobuf:

1.1 通过NuGet包管理器:

拷贝dll:

选择.net2.0的dll:

导入Unity Plugins目录:

1.2 下载源码并生成dll:

GitHub - protocolbuffers/protobuf: Protocol Buffers - Google's data interchange format

解压选择csharp:

VS打开项目:

生成解决方案:

获取dll:

(.net2.0只包含Protobuf.dll,其他dll得从.net45获取)

2. 使用protoc工具获取协议对应的.cs文件:

获取protoc,v3.29.3对应 protoc-29.3-win64.zip,版本对应官方文档有说明;

新建proto文件:

使用protoc获取cs:

3. 在Unity使用cs:

序列化与反序列化工具:

cs 复制代码
public class ProtoTool
{
    /// <summary>
    /// 序列化
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    public static byte[] Serialize(IMessage message)
    {
        return message.ToByteArray();
    }
    /// <summary>
    /// 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="packct"></param>
    /// <returns></returns>
    public static T DeSerialize<T>(byte[] packct) where T : IMessage, new()
    {
        IMessage message = new T();
        try {
            return (T)message.Descriptor.Parser.ParseFrom(packct);
        }
        catch (System.Exception e) {
            throw e;
        }
    }
}

实例:

cs 复制代码
UserInfo send = new UserInfo();
send.Name = "Lin";
send.Gold = 91000000000;
byte[] buff = ProtoTool.Serialize(send);
UserInfo recv = ProtoTool.DeSerialize<UserInfo>(buff);
Debug.Log($"{recv.Name}, {recv.Diamonds}, {recv.Gold}, {recv.Level}");

反序列化时,可从协议生成的类中获取Parser:

参考:在Unity中使用Protobuf进行序列化_unity c# proto buffer-CSDN博客

相关推荐
风痕天际4 小时前
Godot扫雷游戏制作记录1——基础场景搭建
游戏·游戏引擎·godot·gdscript·教程
上证50指数etf6 小时前
Unity面试总结
unity
爱搞虚幻的阿恺20 小时前
Niagara粒子系统-超炫酷的闪电特效(第二期 旋转的纸片)
游戏·游戏引擎·虚幻
WarPigs1 天前
Unity渲染问题记录
unity·游戏引擎
不绝1911 天前
导入3D模型时相关参数设置/Model标签页/Rig标签页/Avatar相关参数/Animation标签页/Materia标签页
unity·游戏程序
dlpay1 天前
使用blender搭建模型并导入godot游戏引擎
游戏引擎·godot·blender
不是AI1 天前
【Unity开发】一、在安卓设备上运行Unity项目
android·unity·游戏引擎
淡海水2 天前
【节点】[EyeSurfaceTypeDebug节点]原理解析与实际应用
unity·游戏引擎·debug·shadergraph·图形·surface·eye
淡海水2 天前
【节点】[IrisLimbalRing节点]原理解析与实际应用
unity·游戏引擎·iris·shadergraph·图形·ring·limbal
在路上看风景2 天前
33. RenderTarget
unity