ProtoBuf在Unity3D中的简单使用!

Posted 阶梯之上

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ProtoBuf在Unity3D中的简单使用!相关的知识,希望对你有一定的参考价值。

目前Unity3D依然是移动手机开发的主流开发工具。

而在移动端推荐的打包解包方法是使用Protobuf协议:主要优点就是效率高,传输量小,节省带宽。而想要在androidios端都能使用Protobuf,我使用的方法是把Protobuf-net源代码拷贝到项目中的Scripts文件夹中,而当拷贝到文件夹时会出现如下错误。(文章结尾附有源代码)


我们只需要在Assets目录下创建smcs.rsp文件,并在文件中写入-unsafe,重新编译,即可发现错误消失。

这样前期配置工作就完成了,下面就是简单的编码部分。

1、首先创建一个cs文件,命名为Person.cs,具体源码如下

[ProtoContract]
public class Person 
    [ProtoMember(1)]
    public int Id  get; set; 
    [ProtoMember(2)]
    public string Name  get; set; 
    [ProtoMember(3)]
    public Address Address  set; get; 

    public override string ToString()
    
        return "Id = " + Id + " " + "Name = " + Name + " " + "Address = " + Address;
    

[ProtoContract]
public class Address

    [ProtoMember(1)]
    public string Line1  get; set; 
    [ProtoMember(2)]
    public string Line2  get; set; 

    public override string ToString()
    
        return "Line1 = " + Line1 + " " + "Line2 = " + Line2;
    
2、在项目中创建一个Test.cs文件,并挂载到Main Camera上
public class Test : MonoBehaviour

    List<Person> persons = new List<Person>();
    void Start()
    
        Person p1 = new Person()
        
            Address = new Address() Line1 = "one line address", Line2 = "two line address",
            Id = 1,
            Name = "肖明"
        ;
        Person p2 = new Person() Address = new Address() Line1 = "one line", Line2 = "two line", Id = 1, Name = "肖红";
        persons.Add(p1);
        persons.Add(p2);
        using (var file = File.Create("test.bin"))//把对象序列化到文件中
        
            Serializer.Serialize(file,persons);
        
     

    void OnGUI()
    
        if (GUILayout.Button("反序列化"))
        
            Deserialize();
        
    

    void Deserialize()
    
        List<Person> personList =new List<Person>();
        using (var file = File.OpenRead("test.bin"))
        
            personList = Serializer.Deserialize<List<Person>>(file);
        

        foreach (var person in personList)
        
            Debug.Log(person);
        
    
3、运行程序,你会发现在你的项目根目录中有一个test.bin文件,里面就存放的是我们被序列化的对象

4、点击场景中的反序列化Button,,会看到输出了如下字符串

5、我简单写了一个protobuf工具类,主要提供把对象序列化到文件或者内存中去,和把文件或者内存中的数据反序列化出来,下面是主要源代码

public class ProtobufHelper

    /// <summary>
    /// 把对象序列化到内存中
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <returns></returns>
    public static string Serialize<T>(T t)
    
        using (MemoryStream ms = new MemoryStream())
        
            Serializer.Serialize(ms, t);
            return Encoding.UTF8.GetString(ms.ToArray());
        
    
    /// <summary>
    /// 把对象序列化到文件中
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="t"></param>
    public static void Serialize<T>(string path, T t)
    
        using (var file = File.Create(path))
        
            Serializer.Serialize(file,t);
        
    
    /// <summary>
    /// 把对象从内存中反序列化回来
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="content"></param>
    /// <returns></returns>
    public static T Deserialize<T>(string content)
    

        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
        
            T t = Serializer.Deserialize<T>(ms);
            return t;
        
    

    /// <summary>
    /// 把对象从文件中反序列化回来
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="s"></param>
    /// <returns></returns>
    public static T Deserialize<T>(Stream s)
    
        return Serializer.Deserialize<T>(s);
    
6、下面是这个类的简单实用方法(把数据序列化到内存中,并把对象从内存中反序列化回来),在Test.cs修改代码如下
public class Test : MonoBehaviour

    List<Person> persons = new List<Person>();
    string strResult = String.Empty;
    void Start()
    
        Person p1 = new Person()
        
            Address = new Address() Line1 = "one line address", Line2 = "two line address",
            Id = 1,
            Name = "肖明"
        ;
        Person p2 = new Person() Address = new Address() Line1 = "one line", Line2 = "two line", Id = 1, Name = "肖红";
        persons.Add(p1);
        persons.Add(p2);
        strResult = ProtobufHelper.Serialize(persons);//序列化到内存中
     

    void OnGUI()
    
        if (GUILayout.Button("反序列化"))
        
            Deserialize();
        
    

    void Deserialize()
    
        List<Person> personList =new List<Person>();
        personList = ProtobufHelper.Deserialize<List<Person>>(strResult);从内存中反序列化出来

        foreach (var person in personList)
        
            Debug.Log(person);
        
    
 
7、下面是把数据序列化到文件中,并把对象从文件中反序列化回来,在Test.cs修改代码如下
public class Test : MonoBehaviour

    List<Person> persons = new List<Person>();
    private string path;
    void Start()
    
        path = Application.streamingAssetsPath + "/test.bin";
        Person p1 = new Person()
        
            Address = new Address() Line1 = "one line address", Line2 = "two line address",
            Id = 1,
            Name = "肖明"
        ;
        Person p2 = new Person() Address = new Address() Line1 = "one line", Line2 = "two line", Id = 1, Name = "肖红";
        persons.Add(p1);
        persons.Add(p2);
        ProtobufHelper.Serialize<List<Person>>(path,persons);//把对象序列化到文件中
     

    void OnGUI()
    
        if (GUILayout.Button("反序列化"))
        
            Deserialize();
        
    

    void Deserialize()
    
        List<Person> personList =new List<Person>();
        using (var file = File.OpenRead(path))//从文件中读取
        
            personList = ProtobufHelper.Deserialize<List<Person>>(file);
        

        foreach (var person in personList)
        
            Debug.Log(person);
        
    
 

8.这就是一个简单的Protobuf序列化与反序列化介绍,我附上protobuf-net源代码供大家下载

链接:http://pan.baidu.com/s/1kUBZDYZ 密码:4b01

以上是关于ProtoBuf在Unity3D中的简单使用!的主要内容,如果未能解决你的问题,请参考以下文章

Protobuf-net 和 Unity3D 类型

针对 iOS 的 Unity3D 中的协议缓冲区

Unity3D游戏GC优化总结---protobuf-net无GC版本优化实践

Unity3D客户端和Java服务端使用Protobuf

Unity3d 学习路线-网络传输协议protobuf

Unity3D —— protobuf网络框架