打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
[Unity3D]简单使用Protobuf

Protobuf 是Google的一个开源序列化库,因为使用的数据压缩算法等优化,序列化的数据较Xml更小,速度更快,因为序列化后数据是以紧凑的二进制流形式展现的,所以几乎不可直接查看。

由于Protobuf不支持.Net3.5及以下版本,所以如果要在Unity3D当中使用,则需要用到第三方的Protobuf-net库。

Protobuf-net也是开源的,项目地址如下:https://github.com/mgravell/protobuf-net

本片文章介绍最简单其最简单的用法,其他用法见后面几篇。

  1. 创建一个C#的控制台程序
  2. 点击项目右键打开“管理NuGet程序包”。
  3. 搜索“Protobuf-net”,并安装,如下:

  4. 编辑测试代码如下:

using System.Collections.Generic;using System.IO;namespace ProtoTest_1{    [ProtoBuf.ProtoContract]    class MyClass    {        [ProtoBuf.ProtoMember(1)]        public int _nNumber;        [ProtoBuf.ProtoMember(2)]        public string _strName;        [ProtoBuf.ProtoMember(3)]        public List<string> _lstInfo;        [ProtoBuf.ProtoMember(4)]        public Dictionary<int, string> _dictInfo;    }    class Program    {        static void Main(string[] args)        {            //测试用数据            MyClass my = new MyClass();            my._nNumber = 0;            my._strName = "test";            my._lstInfo = new List<string>();            my._lstInfo.Add("a");            my._lstInfo.Add("b");            my._lstInfo.Add("c");            my._dictInfo = new Dictionary<int, string>();            my._dictInfo.Add(1, "a");            my._dictInfo.Add(2, "b");            my._dictInfo.Add(3, "c");            using (FileStream stream = File.OpenWrite("test.dat"))            {                //序列化后的数据存入文件                ProtoBuf.Serializer.Serialize<MyClass>(stream, my);            }            MyClass my2 = null;            using (FileStream stream = File.OpenRead("test.dat"))            {                //从文件中读取数据并反序列化                my2 = ProtoBuf.Serializer.Deserialize<MyClass>(stream);            }        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

以上程序实现了MyClass类的序列化与反序列化操作,是不是很简单!

需要注意的是序列化类的类名前需要加上“[ProtoBuf.ProtoContract]”,然后每个字段需要按照顺序在前面加上“[ProtoBuf.ProtoMember(Index)]”,这样才能使用。
后面将继续讲解protobuf-net的使用动态链接库和直接使用源码的这两种方式。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Protobuf的序列化与反序列化
序列化悍将Protobuf
Unity3D客户端和Java服务端使用Protobuf
ProtoBuf 常用序列化/反序列化API
Java对象XML序列化框架-Simple2.0
Unity手游之路<一>C#版本Protobuf
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服