Unity当中使用Protobuf-net进行序列化和反序列化

probuffer-net可以在https://code.google.com/p/protobuf-net/downloads/list下载(需翻墙)
或者我创建了一个百度云网盘大家可以下载链接:https://pan.baidu.com/s/1OUnfba8CeZ27PKEOtz3mlg 提取码: qrf9
首先我们要创建一个Test.proto文件来进行测试

message ReqLogin {
	optional string account = 1; // 账号
	optional string password = 2; // 密码
}

我们这里要用到一个工具ProtoGen,这个工具在我上传的百度云网盘里或者我给出的google的那个网站中也有下载
为了快捷编译我创建了一个批处理文件run.bat

@echo off
for /f "delims=" %%i in ('dir /b proto "proto/*.proto"') do protogen -i:proto/%%i -o:cs/%%~ni.cs
pause

这个文件的意思是会编译proto文件夹下的.proto文件为.cs文件并放在cs文件夹下
如图所示路径即可正常编译
路径是这样子摆放
将.proto文件放入proto文件夹下双击运行run.bat。会在cs文件夹下生成test.cs文件。打开来是这样的

namespace proto.Test
{
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ReqLogin")]
  public partial class ReqLogin : global::ProtoBuf.IExtensible
  {
    public ReqLogin() {}
    
    private string _account = "";
    [global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"account", DataFormat = global::ProtoBuf.DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string account
    {
      get { return _account; }
      set { _account = value; }
    }
    private string _password = "";
    [global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"password", DataFormat = global::ProtoBuf.DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string password
    {
      get { return _password; }
      set { _password = value; }
    }
    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }
  
}

即表示编译成功。

接下来我们要进行序列化和反序列化的工作
创建一个Unity工程。新建一个文件夹名为Plugins将ProGen文件夹下的protobuf-net.dll文件放入此文件夹。
然后将前面编译完成的Test.cs文件放入工程中。
目录结构如下所示
在这里插入图片描述
这里只是demo所以不创建Secens文件夹和Scripts文件夹了

在Unity工程中新建cs文件名为TestProbuffer。代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;
using System.IO;
using proto.Test;
public class TestProbuffer : MonoBehaviour {

    byte[] testByte;
    // Use this for initialization
    void Start () {
        ReqLogin reqLogin = new ReqLogin();
        reqLogin.account = "oneSitDown";
        reqLogin.password = "2222";
        testByte = Serialize(reqLogin);
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Space))
        {
            ReqLogin reqLogin = (ReqLogin)Deserialize<ReqLogin>(testByte);
            Debug.Log(reqLogin.account);
            Debug.Log(reqLogin.password);
        }
	}


    public byte[] Serialize(IExtensible msg)
    {
        byte[] result;
        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, msg);
            result = stream.ToArray();
        }
        return result;
    }

    public IExtensible Deserialize<IExtensible>(byte[] message)
    {
        IExtensible result;
        using (var stream = new MemoryStream(message))
        {
            result = Serializer.Deserialize<IExtensible>(stream);
        }
        return result;
    }
}

将脚本挂在场景的任意物体下,然后运行工程,按下空格键。会输出文字即表示操作成功。
工程的地址为 https://github.com/oneSitDown/probufMessage

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 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值