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

相关推荐
松树戈14 小时前
godot项目【宝石捕手】04~添加音效、记分
游戏引擎·godot
LONGZETECH17 小时前
无人机实训高成本痛点解法:虚拟仿真实现 70% 耗材损耗下降
大数据·算法·unity·架构·无人机
五仁烧饼1 天前
Unity Addressables 静默资源策略
游戏·unity·addressables
ue星空2 天前
【Godot】更换编辑器外观主题
编辑器·游戏引擎·godot
fanfan_hongyun2 天前
unity 与cad 坐标系映射
unity·游戏引擎
神码编程2 天前
【Unity】 HTFramework框架(七十)MultiChoiceDropdown可多选的下拉菜单
unity·游戏引擎·ugui·dropdown·下拉菜单
ue星空2 天前
Godot 2D像素游戏移动抖动、模糊问题解决方案
游戏·游戏引擎·godot
淡海水2 天前
15-07-YooAsset面试篇-Unity性能优化与内存管理
java·unity·面试·性能优化·c#·游戏引擎
ue星空2 天前
【Godot】AudioStreamPlayer2D音频播放
游戏引擎·音视频·godot
zhchyun20083 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(03)
unity