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

相关推荐
RReality2 小时前
【Unity UGUI】Toggle / ToggleGroup 与 Dropdown
ui·unity·游戏引擎·图形渲染·材质
雪儿waii3 小时前
Unity 中的 InvokeRepeating 详解
unity·游戏引擎
mxwin3 小时前
Unity Shader 程序化生成:Shader 中的数学宇宙
unity·游戏引擎
雪儿waii5 小时前
Unity 中的 Quaternion(四元数)详解
unity·游戏引擎
RReality5 小时前
【Unity UGUI】ScrollRect 与 Scrollbar 深度用法
unity·游戏引擎
人邮异步社区5 小时前
如何自学游戏引擎的开发?
unity·程序员·游戏引擎
郝学胜-神的一滴6 小时前
[简化版 Games 101] 计算机图形学 05:二维变换下
c++·unity·图形渲染·three.js·opengl·unreal
mxwin19 小时前
Unity URP 热更新兼容性:Shader 在 IL2CPP 打包下的注意事项
unity·游戏引擎
mxwin1 天前
Unity shader中TransformWorldToShadowCoord原理解析
unity·游戏引擎·shader
mxwin1 天前
Unity Shader 中 ShadowCaster的作用和疑问
unity·游戏引擎