1.协议定义,简单实现传玩家的2D坐标
syntax = "proto3";
package SocketGameProtocol;
message PlayerInfo
{
float xPos=1;
float yPos=2;
}
2.在Unity的Assets目录下创建一个Plugins文件夹(必须这样命名),此文件专门存放扩展文件,
再新建文件夹BaseInfolibrary,将Google.Protobuf.dll拖入
3.新建一个Test.cs脚本
脚本中引入命名空间
using SocketGameProtocol;
using Google.Protobuf;
using System;
using System.IO;
private PlayerInfo info;
public byte[] Init(Vector2 pos)
{
if (info == null)
{
info = new PlayerInfo();
}
info.XPos = pos.x;
info.YPos = pos.y;
byte[] data = Serialize(info);
return data;
}
//序列化
private byte[] Serialize(PlayerInfo model)
{
try {
using (MemoryStream ms = new MemoryStream()) {
model.WriteTo(ms);
return ms.ToArray();
}
} catch (Exception ex) {
Debug.Log ("序列化失败: " + ex.ToString());
return null;
}
}
//反序列化
private PlayerInfo DeSerialize(byte[] data)
{
return PlayerInfo.Parser.ParseFrom(data);
}
后续
代码改进:通用序列化模板(只用来序列化Message)
/// <summary>
/// 序列化protobuf
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public static byte[] SerializeMsg(IMessage msg)
{
using (MemoryStream rawOutput = new MemoryStream())
{
msg.WriteTo(rawOutput);
byte[] result = rawOutput.ToArray();
return result;
}
}
/// <summary>
/// 反序列化protobuf
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataBytes"></param>
/// <returns></returns>
public static T DeserializeMsg<T>(byte[] dataBytes) where T : IMessage, new()
{
T msg = new T();
msg= (T)msg.Descriptor.Parser.ParseFrom(dataBytes);
return msg;
}
序列化前提还是要知道消息的类型,以下是调用
文章来源:https://www.toymoban.com/news/detail-556571.html
文章来源地址https://www.toymoban.com/news/detail-556571.html
到了这里,关于Unity基于Google Protobuf序列化和反序列化小案例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!