Unity uses Protobuf serialization and deserialization

using System.Collections ; using
System.Collections.Generic
;
using     UnityEngine
; using ProtoBuf
; Indicates that the field can be serialized, 1 can understand the subscript     [ProtoMember(1)]     public int ID;     [ProtoMember(2)]     public int Drag;     public DragMsg()     {     }     public DragMsg(int bikeId, int drag)     {         ID = bikeId;         Drag = drag;     } } public class Test2 : MonoBehaviour {




















    // Start is called before the first frame update
    void Start()
    {
        byte[] result = Serialize();
        DragMsg d = DeSerialize<DragMsg>(result);
        Debug.Log(d.Drag + "     " + d.ID);
    }

    /// <summary>
    /// Serialize the message to binary
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public static byte [] Serialize()
    {         DragMsg drag = new DragMsg(123, 123);

        try
        {             //Involving format conversion, need to use stream, serialize binary into stream               using (MemoryStream ms = new MemoryStream())             {                 //Use the serialization method of ProtoBuf tool                   Serializer.Serialize(ms, drag);                 / /Define a binary system array to save the serialized result                   byte[] result = new byte[ms.Length];                 //Set the position of the stream to 0, and the starting point                   ms.Position = 0;                 //Set the position of the stream to 0 Read the content into the binary array                   ms.Read(result, 0, result.Length);                 return result;             }         }         catch (Exception ex)         {             return null;

















        }
    }
    /// <summary>
    /// deserialized message
    /// </summary>
    /// <typeparam name="T">message type</typeparam>
    /// <param name="msg"> Binary message body</param>
    /// <returns>Message body</returns>
    public T DeSerialize<T>(byte[] msg)
    {         using (MemoryStream ms = new MemoryStream())         {             //Write the message to the stream Medium               ms.Write(msg, 0, msg.Length);             //Set the position of the stream to 0               ms.Position = 0;             //Use the tool to deserialize the object               T result = default(T);             result = Serializer.Deserialize<T>(ms);             return result;         }











    }
}
 

Guess you like

Origin blog.csdn.net/LuffyZ/article/details/108865485