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

相关推荐
qq_2052790512 小时前
Unity TileMap 使用经验
unity·游戏引擎
心灵宝贝14 小时前
Mac Unity 2018.dmg游戏工具 安装步骤 简单易懂教程(附安装包)
macos·unity·游戏引擎
TO_ZRG15 小时前
Unity SDK 通过 Registry 分发及第三方依赖处理指南
unity·游戏引擎
7***n7520 小时前
C++在游戏中的Cocos2d-x
游戏·游戏引擎·cocos2d
龙智DevSecOps解决方案1 天前
Perforce《2025游戏技术现状报告》Part 1:游戏引擎技术的广泛影响以及生成式AI的成熟之路
人工智能·unity·游戏引擎·游戏开发·perforce
Y***K4341 天前
C在游戏中的Godot
游戏·游戏引擎·godot
WarPigs2 天前
Unity编辑器开发笔记
unity·编辑器·excel
Q***f6352 天前
C++在游戏引擎开发中的实践
游戏引擎
6***x5452 天前
C++在计算机视觉中的图像处理
c++·图像处理·计算机视觉·游戏引擎·logback·milvus
霜绛2 天前
Unity:lua热更新(三)——Lua语法(续)
unity·游戏引擎·lua