当前位置 : 主页 > 大数据 > 区块链 >

Protobuf在Unity中的通讯使用

来源:互联网 收集:自由互联 发布时间:2021-06-22
代码很简单直接上了 using ProtoBuf; using UnityEngine; using System.IO; using System; public class Test2 : MonoBehaviour { private void Start() { NetModel item = new NetModel() { ID = 1, Commit = "LZ", Message = "Unity" }; byte[] re

代码很简单直接上了

 

using ProtoBuf;
using UnityEngine;
using System.IO;
using System;

public class Test2 : MonoBehaviour
{

private void Start()
{
NetModel item = new NetModel()
{
ID = 1,
Commit = "LZ",
Message = "Unity"
};

byte[] result = Serialize<NetModel>(item);

NetModel backIns = DeSerialize<NetModel>(result);
Debug.Log(backIns.ID);
Debug.Log(backIns.Commit);
Debug.Log(backIns.Message);


}

public byte[] Serialize<T>(T classValue)
{

try
{
using (MemoryStream memory = new MemoryStream())
{
Serializer.Serialize<T>(memory, classValue);
byte[] result = new byte[memory.Length];
memory.Position = 0;
memory.Read(result, 0, result.Length);
return result;
}
}

catch (Exception e)
{
Debug.Log(e);
return null;
}

}

public T DeSerialize<T>(byte[] value) //where T : class // 这里可以做个约束class类型, 也可以做个基佬,让所有序列化类继承之再去约束这个类更安全
{


try
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(value, 0, value.Length);
ms.Position = 0;
return Serializer.Deserialize<T>(ms);

}
}
catch(Exception e)
{
Debug.Log("Error:"+e);
return default(T);
}


}

[ProtoContract]
public class NetModel
{
[ProtoMember(1)]
public int ID;
[ProtoMember(2)]
public string Commit;
[ProtoMember(3)]
public string Message;


}

}

网友评论