一个游戏包含了各种数据,包括本地数据和与服务端通信的数据。今天我们来谈谈如何存储数据,以及客户端和服务端的编码方式。根据以前的经验,我们可以用字符串,XML,json...甚至可以直接存储二进制。各种方式都有各自的优劣,有些性能比较好,但是实现方式比较麻烦。有些数据冗余太多。 简介 今天我们来学习一种广泛使用的数据格式:Protobuf。简单来说,它就是一种二进制格式,是google发起的,目前广泛应用在各种开发语言中。具体的介绍可以参见:https://code.google.com/p/protobuf/ 。我们之所以选择protobuf,是基于它的高效,数据冗余少,编程简单等特性。关于C#的protobuf实现,网上有好几个版本,公认比较好的是Protobuf-net。实例 先来看一个最简单的例子:把一个类用Protobuf格式序列化到一个二进制文件。再读取二进制数据,反序列化出对象数据。
//----------------实体类----------------------
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 data
{
get;
set;
}
public override string ToString()
{
String str = Id+:;
foreach (String d in data)
{
str += d + ,;
}
return str;
}
}
//-----------测试类---------------------------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 testData = new List();
for (int i = 0; i < 100; i++)
{
testData.Add(new Test() { Id = i, data = new List(new string[]{1,2,3}) });
}
//将数据序列化后存入本地文件
using(Stream file = File.Create(PATH))
{
Serializer.Serialize>(file, testData);
file.Close();
}
//将数据从文件中读取出来,反序列化
List fileData;
using (Stream file = File.OpenRead(PATH))
{
fileData = Serializer.Deserialize>(file);
}
//打印数据
foreach (Test data in fileData)
{
Debug.Log(data);
}
}
}
总结
Protobuf-net 利用Attributes来实现序列化字段,对程序员的负担减轻,代码侵入性也降低。接下来,我将会写一个简单的Unity c/s demo,其中的通信编码就是用到Protobuf,
到时再与大家分享。