GoogleProtobuf使用
下载Protobuf
Google Protobuf:down
生成c#文件
使用protobuf生成的C#代码,继承了序列化和反序列化的类,该类就是一些繁琐的字符串处理逻辑,反序列化采用反射机制实现
- 创建.proto文件,使用proto的语法编写需要序列化和反序列化的class
syntax="proto3"; // 使用协议版本
package zhanghj; // namespace
message DataInfo {
string name = 1; // 字段序列化顺序
int32 id = 2;
string hobby = 3;
}
- 编写.bat文件,主要是指明协议版本,语言类型,文件输出输入路径
C:
cd C:\Users\zhanghj\Documents\C#\Utils\protoc-3.20.2-win64\bin
protoc.exe --proto_path ./ DataInfoProto.proto --csharp_out=./
echo Exprot Successed!
pause
- 点击.bat文件生成对应C#文件
Unity操作
- 将C#文件放入Unity中,会有error,因为序列化和反序列化的功能类没有导入,点击vs的工具>NuGet>解决方案,搜索Googleprotobuf,下载第一个,将会在unity的Asset同级目录的Package目录下生成一堆.dll文件。将以下四个文件导入Unity中。
- 编写序列化和反序列化函数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Google.Protobuf;
public class Protobuffer
{
public static byte[] Serialize(IMessage message) {
return message.ToByteArray();
}
public static T DeSerialize<T>(byte[] packet) where T : IMessage, new() {
IMessage message = new T();
try {
return (T)message.Descriptor.Parser.ParseFrom(packet);
} catch(System.Exception e) {
throw;
}
}
}
- 测试
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Zhanghj;
public class Controller : MonoBehaviour {
// Start is called before the first frame update
void Start() {
DataInfo data = new DataInfo();
data.Name = "楚子航";
data.Id = 1;
data.Hobby = "屠龙";
byte[] bits = Protobuffer.Serialize(data);
Debug.Log("序列化成功!序列化后长度是:" + bits.Length);
DataInfo res = Protobuffer.DeSerialize<DataInfo>(bits);
Debug.Log("反序列化成功!name:" + res.Name);
}
// Update is called once per frame
void Update() {
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!