您的位置:首页 > 移动开发 > Unity3D

Unity手游之路<一>C#版本Protobuf

2014-05-26 19:18 381 查看
一个游戏包含了各种数据,包括本地数据和与服务端通信的数据。今天我们来谈谈如何存储数据,以及客户端和服务端的编码方式。根据以前的经验,我们可以用字符串,XML,json...甚至可以直接存储二进制。各种方式都有各自的优劣,有些性能比较好,但是实现方式比较麻烦。有些数据冗余太多。

简介

今天我们来学习一种广泛使用的数据格式:Protobuf。简单来说,它就是一种二进制格式,是google发起的,目前广泛应用在各种开发语言中。具体的介绍可以参见:https://code.google.com/p/protobuf/ 。我们之所以选择protobuf,是基于它的高效,数据冗余少,编程简单等特性。关于C#的protobuf实现,网上有好几个版本,公认比较好的是Protobuf-net。

实例

先来看一个最简单的例子:把一个类用Protobuf格式序列化到一个二进制文件。再读取二进制数据,反序列化出对象数据。

从网上参考了一个例子 http://blog.csdn.net/ddxkjddx/article/details/7239798
//----------------实体类----------------------

[csharp]
view plaincopy





using UnityEngine;
using System.Collections;
using ProtoBuf;
using System;
using System.Collections.Generic;

[ProtoContract]
public class Test {

[ProtoMember(1)]
public int Id
{
get;
set;
}

[ProtoMember(2)]
public List<String> data
{
get;
set;
}

public override string ToString()
{
String str = Id+":";
foreach (String d in data)
{
str += d + ",";
}
return str;
}

}

//-----------测试类---------------------------

[csharp]
view plaincopy





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

public class ProtobufNet : MonoBehaviour {

private const String PATH = "c://data.bin";

void Start () {
//生成数据
List<Test> testData = new List<Test>();
for (int i = 0; i < 100; i++)
{
testData.Add(new Test() { Id = i, data = new List<string>(new string[]{"1","2","3"}) });
}
//将数据序列化后存入本地文件
using(Stream file = File.Create(PATH))
{
Serializer.Serialize<List<Test>>(file, testData);
file.Close();
}
//将数据从文件中读取出来,反序列化
List<Test> fileData;
using (Stream file = File.OpenRead(PATH))
{
fileData = Serializer.Deserialize<List<Test>>(file);
}
//打印数据
foreach (Test data in fileData)
{
Debug.Log(data);
}
}

}

总结

Protobuf-net 利用Attributes来实现序列化字段,对程序员的负担减轻,代码侵入性也降低。接下来,我将会写一个简单的Unity c/s demo,其中的通信编码就是用到Protobuf,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: