Unity插件学习(一) ------ Protobuf-net插件学习

protobuf是google的一个开源项目,可用于以下两种用途:
(1)数据的存储(序列化和反序列化),类似于xml、json等;
(2)制作网络通信协议。

protobuf比XML、比JSON更为强悍,语言无关、平台无关、更小的存储、更少的歧义、更高的性能

插件下载地址:https://github.com/mgravell/protobuf-net(源码,还需要自己打包成dll)

dll直接下载地址:https://code.google.com/archive/p/protobuf-net/downloads(需要翻墙)

百度网盘分享链接:https://pan.baidu.com/s/1uO_VJGjPwasV_Lfny3zBFw 密码:7qfg


下载好后,直接在protobuf-net r668\Full\unity里面可以找到protobuf-net.dll,直接导入到unity 里面的Plugins文件里面就可以使用了。

                                                               

首先创建一个类:

using ProtoBuf;

[ProtoContract] //表示这个类的对象要作为Protobuf传输的对象
public class User  {
    [ProtoMember(1)] //指定Tag,不能重复,标识其属于哪个字段,使用数字标识所占空间小
    public int ID { get; set; }
    [ProtoMember(2)]
    public string Username { get; set; }
    [ProtoMember(3)]
    public string Password { get; set; }
    [ProtoMember(4)]
    public int Level { get; set; }
    [ProtoMember(5)]
    public UserType _UserType { get; set; }

    public enum UserType
    {
        Master,
        Warrior
    }
}

  • 序列化:
 User user = new User();
        user.ID = 100;
        user.Username = "qianxi";
        user.Password = "123456";
        user.Level = 100;
        user._UserType = User.UserType.Master;
        FileStream fs = File.Create(Application.dataPath + "/user.bin");//二进制文件
        print(Application.dataPath + "/user.bin");
        Serializer.Serialize<User>(fs, user); //将对象进行序列化放在fs打开的文件中
        fs.Close();
输入流优化写法:
 //using表示{ }中使用fs,外部无法使用fs,会自动close
        using (var fs = File.Create(Application.dataPath + "/user.bin"))
        {
            Serializer.Serialize<User>(fs, user);
        }

运行:


  • 反序列化
        User user = null;
        using (var fs = File.OpenRead(Application.dataPath + "/user.bin"))
        {
            user = Serializer.Deserialize<User>(fs);
        }
        print(user.ID);
        print(user._UserType);
        print(user.Username);
        print(user.Password);
        print(user.Level);



猜你喜欢

转载自blog.csdn.net/dengshunhao/article/details/80560472