using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;
using System;
using System.IO;
//添加特性,表示可以被ProtoBuf工具序列化
[ProtoContract]
public class DragMsg
{
//添加特性,表示该字段可以被序列化,1可以理解下标
[ProtoMember(1)]
public int ID;
[ProtoMember(2)]
public int Drag;
public DragMsg()
{
}
public DragMsg(int bikeId, int drag)
{
ID = bikeId;
Drag = drag;
}
}
public class Test2 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
byte[] result = Serialize();
DragMsg d = DeSerialize<DragMsg>(result);
Debug.Log(d.Drag + " " + d.ID);
}
/// <summary>
/// 将消息序列化为二进制
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static byte[] Serialize()
{
DragMsg drag = new DragMsg(123, 123);
try
{
//涉及格式转换,需要用到流,将二进制序列化到流中
using (MemoryStream ms = new MemoryStream())
{
//使用ProtoBuf工具的序列化方法
Serializer.Serialize(ms, drag);
//定义二级制数组,保存序列化后的结果
byte[] result = new byte[ms.Length];
//将流的位置设为0,起始点
ms.Position = 0;
//将流中的内容读取到二进制数组中
ms.Read(result, 0, result.Length);
return result;
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 反序列化消息
/// </summary>
/// <typeparam name="T">消息类型</typeparam>
/// <param name="msg">二进制消息体</param>
/// <returns>消息体</returns>
public T DeSerialize<T>(byte[] msg)
{
using (MemoryStream ms = new MemoryStream())
{
//将消息写入流中
ms.Write(msg, 0, msg.Length);
//将流的位置归0
ms.Position = 0;
//使用工具反序列化对象
T result = default(T);
result = Serializer.Deserialize<T>(ms);
return result;
}
}
}