ProtobufHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using ProtoBuf.Meta;
  5. using Unity.Mathematics;
  6. namespace ET
  7. {
  8. public static class ProtobufHelper
  9. {
  10. public static void Init()
  11. {
  12. }
  13. static ProtobufHelper()
  14. {
  15. RuntimeTypeModel.Default.Add(typeof(float2), false).Add("x", "y");
  16. RuntimeTypeModel.Default.Add(typeof(float3), false).Add("x", "y", "z");
  17. RuntimeTypeModel.Default.Add(typeof(float4), false).Add("x", "y", "z", "w");
  18. RuntimeTypeModel.Default.Add(typeof(quaternion), false).Add("value");
  19. }
  20. public static object Deserialize(Type type, byte[] bytes, int index, int count)
  21. {
  22. using MemoryStream stream = new MemoryStream(bytes, index, count);
  23. object o = ProtoBuf.Serializer.Deserialize(type, stream);
  24. if (o is ISupportInitialize supportInitialize)
  25. {
  26. supportInitialize.EndInit();
  27. }
  28. return o;
  29. }
  30. public static byte[] Serialize(object message)
  31. {
  32. using MemoryStream stream = new MemoryStream();
  33. ProtoBuf.Serializer.Serialize(stream, message);
  34. return stream.ToArray();
  35. }
  36. public static void Serialize(object message, Stream stream)
  37. {
  38. ProtoBuf.Serializer.Serialize(stream, message);
  39. }
  40. public static object Deserialize(Type type, Stream stream)
  41. {
  42. try
  43. {
  44. object o = ProtoBuf.Serializer.Deserialize(type, stream);
  45. if (o is ISupportInitialize supportInitialize)
  46. {
  47. supportInitialize.EndInit();
  48. }
  49. return o;
  50. }
  51. catch (Exception)
  52. {
  53. Log.Error($"协议数据反序列化时出错了,通常原因是协议更改后,前后端未一起更新编译, Type:{type}");
  54. return null;
  55. }
  56. }
  57. }
  58. }