using System;
//需要用到MemoryStream
using System.IO;
using UnityEngine;
//引入ProtoBuf命名空间
using ProtoBuf;
///
/// 测试类
///
public class TestProtobuf : MonoBehaviour {
///
/// 用于测试的数据类
///
[ProtoContract] //声明这个类能被序列化
public class UserData
{
//声明每一个需要被序列化的成员,编号从1开始
[ProtoMember(1)]
public int id;
[ProtoMember(2)]
public string name;
[ProtoMember(3)]
public int level;
}
//测试代码
void Start()
{
//将要被序列化的UserData示例
UserData user1 = new UserData ();
user1.id = 1;
user1.name = "User1";
user1.level = 10;
//打印user1
Debug.Log (string.Format ("user1-> id:{0}, name:{1}, level:{2}", user1.id, user1.name, user1.level));
//序列化
byte[] buff = null;
using (MemoryStream ms = new MemoryStream ()) {
Serializer.Serialize (ms, user1);
ms.Position = 0;
int length = (int)ms.Length;
buff = new byte[length];
ms.Read (buff, 0, length);
}
//输出字节数组
Debug.Log (string.Format("Serialized data-> {0}", BitConverter.ToString(buff)));
//反序列化
UserData user2 = default(UserData);
using (MemoryStream ms = new MemoryStream (buff)) {
user2 = Serializer.Deserialize (ms);
}
//打印反序列化生成的user2
Debug.Log (string.Format ("user2-> id:{0}, name:{1}, level:{2}", user2.id, user2.name, user2.level));
}
}
作者:qufangliu
链接:https://www.jianshu.com/p/d9be1b3d2446
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1