1. Protocol definition, simple implementation of transmitting the player's 2D coordinates
syntax = "proto3";
package SocketGameProtocol;
message PlayerInfo
{
float xPos=1;
float yPos=2;
}
2. Create a Plugins folder (must be named like this) in the Assets directory of Unity. This file is dedicated to storing extension files.
Create a new folder BaseInfolibrary and drag Google.Protobuf.dll into it
3. Create a new Test.cs script
Introducing namespaces in scripts
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);
}
Follow up
Code improvement: generic serialization template (only used to serialize 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;
}
The premise of serialization is still to know the type of the message, the following is the call