Protobuf-net provides an easy-to-use data serialization scheme that serializes class instances with [Protocontract] features and supports Unity's various publishing platforms, and is highly efficient and user-friendly.
1 Public Static classSerialization2 {3 Public Static byte[] serialize<t>(T instance)4 {5 byte[] bytes;6 using(varms =NewMemoryStream ())7 {8 Serializer.serialize (MS, instance);9bytes =New byte[Ms. Position];Ten varFullbytes =Ms. GetBuffer (); One array.copy (fullbytes, Bytes, bytes. Length); A } - returnbytes; - } the - Public StaticT deserialize<t> (Objectobj) - { - byte[] bytes = (byte[]) obj; + using(varms =NewMemoryStream (bytes)) - { + returnSerializer.deserialize<t>(MS); A } at } -}
The following is an example of a class definition that needs to be serialized.
1 [Protocontract]2 Public classExample3 {4 //PROTOBUF Requirements5 //member without [Protomember] C # attribute whose value will not be serialized6 //isrequired is optional7 //if the member is a custom class object, that is, the class is a nested class, the ordinal must be the same as the first member ordinal in a class member object8 //if all custom class members are expanded in this class, the same ordinal cannot exist9 Ten Public intClassName {Get;Set; } One A[Protomember (1, isrequired =true)] - Publicdictionary<int,int> Dictionary {Get;Set; } - the //must have a parameterless default constructor - PublicExample () - { -Dictionary =Newdictionary<int,int>(); + } -}
Unity uses protobuf-net for binary serialization and deserialization