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博客

相关推荐
切韵10 天前
Unity编辑器扩展:UI绑定复制工具
ui·unity·编辑器
10 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
深空数字孪生10 天前
2025年小程序地图打车的5大技术革新:实时路况预测与智能调度升级
大数据·人工智能·unity·性能优化·小程序·游戏引擎
RPGMZ10 天前
RPGMZ 游戏引擎如何与lua进行互相调用 初探
开发语言·javascript·游戏引擎·lua·rpgmz
程序猿多布10 天前
Unity Addressable使用之检测更新流程
unity·addressable
Bunny Chen11 天前
Unity中的物理单位是真实的吗?
unity·游戏引擎
benben04411 天前
Unity3D仿星露谷物语开发69之动作声音
游戏·ui·unity·c#·游戏引擎
徐子竣11 天前
Unity Shader开发-着色器变体(1)-着色器变体概述
unity·游戏引擎·着色器
playmak3r12 天前
某手游cocos2dlua反编译
游戏引擎·lua·cocos2d
Magnum Lehar12 天前
wpf3d游戏引擎ProjectLayoutView实现
游戏引擎·wpf