You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
2.0 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using System.Runtime.Serialization;
  5. using System.IO;
  6. using UnityEngine;
  7. namespace Networking
  8. {
  9. public static class Utility
  10. {
  11. public static byte[] ObjectToByteArray<T>(T obj)
  12. {
  13. if (obj == null)
  14. return null;
  15. BinaryFormatter bf = new BinaryFormatter();
  16. SurrogateSelector surrogateSelector = new SurrogateSelector();
  17. Vector3SerializationSurrogate vector3SS = new Vector3SerializationSurrogate();
  18. ColorSerializationSurrogate colorSS = new ColorSerializationSurrogate();
  19. surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), vector3SS);
  20. surrogateSelector.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), colorSS);
  21. bf.SurrogateSelector = surrogateSelector;
  22. MemoryStream ms = new MemoryStream();
  23. bf.Serialize(ms, obj);
  24. return ms.ToArray();
  25. }
  26. public static T ByteArrayToObject<T>(byte[] arrBytes)
  27. {
  28. MemoryStream memStream = new MemoryStream();
  29. BinaryFormatter bf = new BinaryFormatter();
  30. SurrogateSelector surrogateSelector = new SurrogateSelector();
  31. Vector3SerializationSurrogate vector3SS = new Vector3SerializationSurrogate();
  32. ColorSerializationSurrogate colorSS = new ColorSerializationSurrogate();
  33. surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), vector3SS);
  34. surrogateSelector.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), colorSS);
  35. bf.SurrogateSelector = surrogateSelector;
  36. memStream.Write(arrBytes, 0, arrBytes.Length);
  37. memStream.Seek(0, SeekOrigin.Begin);
  38. T obj = (T)bf.Deserialize(memStream);
  39. return obj;
  40. }
  41. }
  42. }