Unity环境下使用GoogleProtoBuf

来源:互联网 发布:java 7 8 新特性 编辑:程序博客网 时间:2024/05/25 18:09

Google ProtoBuf 是谷歌提供的一套序列化库,可用于网络通信中数据的序列化。由于Unity大部分的编码环境使用的是C#,所以今天介绍一个.net版本的 ProtoBuf 。

该库下载地址:http://code.google.com/p/protobuf-net/downloads/list

      图片
      
其根目录文件如下:
图片
其Full文件夹下视图:
图片
每个平台或体系结构都有一个对应的库,调试文件,提供与IDE可视化Dll信息的一个xml文件( 主要摘些Dll中的体系结构,包括结构中的函数变量申明和使用说明等 ),在这里我选择的当然是Unity,当然这里我们使用的主要是Dll,其他文件就无需理会了。
图片

打开MonoIDE左边工程视图中,默认是这个样子。
图片
然后在Unity Project视口,Assets根目录下,创建层级文件夹,Plugins->ProtoBuf,然后将ProtoBuf-net.dll拖进ProtoBuf文件夹下。Plugins直译是插件的意思,ProtoBuf当然就是程序集命名空间的名字了。
图片
此时再切换到MonoIDE,你会发现它已经更新引用程序集了。
图片
我们双击Protobuf-net.dll可以像Vs2012中一样查看程序集内包含的所有东西。
图片
 新建TestGoogleProtoBuf.cs,键入以下源码。

using UnityEngine;
using System.Collections;
using System.IO;
using ProtoBuf;
using ProtoBuf.Meta;

[ProtoContract]
public class msg_test_data 
{
[ProtoMember(1)]
public int  vI          { get; set; } 
public bool vISpecified { get; set; }
[ProtoMember(2)]
public float vF          { get; set; }
public bool  vFSpecified { get; set; }
[ProtoMember(3)]
public string[] vStr { get; set; }
}

public class TestGoogleProtoBuf : MonoBehaviour {
// Use this for initialization
void Start () 
{
msg_test_data serializeData = new msg_test_data();
serializeData.vI    = -1;
serializeData.vF    = -1000000f;
serializeData.vFSpecified = true;
serializeData.vISpecified = false;
serializeData.vStr = new string[2]
{
    "我叫杨太彦",
    "我正在学习序列化"
};
MemoryStream stream = new MemoryStream();
Debug.Log(string.Format("Stream size of before the write:{0}", stream.Length));
Debug.Log(string.Format("Before the serialize Int:{0} , Float:{1}",
                        serializeData.vI, serializeData.vF));
System.Action<string[]> action = (p) =>
{
if (p != null)
{
Debug.Log(string.Format("Array Length:{0}", p.Length));
foreach (string one in p) 
{
Debug.Log(string.Format("printf:Str{0}",one));
}
}
};
action(serializeData.vStr);
ProtoBuf.Serializer.Serialize<msg_test_data>(stream, serializeData);
Debug.Log(string.Format("Stream size of after the wirte:{0}",stream.Length));
MemoryStream  stream2 = new MemoryStream(stream.ToArray(), 0, (int)stream.Length, false);
msg_test_data result  = ProtoBuf.Serializer.Deserialize<msg_test_data>(stream2);
Debug.Log(string.Format("After the serialize Int:{0} , Float:{1}", 
                        result.vI, result.vF)); 
action(result.vStr);            
stream.Close(); 
}

检查错误无误后将脚本挂在摄像机上,运行游戏,这里int的写入权为false,不占用任何字节,输出结果同样为0,字符串占用43字节,Float占用了5字节,完全正确
图片 

TheEnd.. 

0 0
原创粉丝点击