一个游戏包含了各种数据,包括本地数据和与服务端通信的数据。今天我们来谈谈如何存储数据,以及客户端和服务端的编码方式。根据以前的经验,我们可以用字符串,XML,json...甚至可以直接存储二进制。各种方式都有各自的优劣,有些性能比较好,但是实现方式比较麻烦。有些数据冗余太多。
- 简介
- 实例
从网上参考了一个例子 http://blog.csdn.net/ddxkjddx/article/details/7239798
//----------------实体类----------------------
- 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;
- }
- }
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;
}
}
//-----------测试类---------------------------
- 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);
- }
- }
- }
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,
到时再与大家分享。有任何问题欢迎一起探讨ken@iamcoding.com