ObjectSerializationExtension.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using System.IO;
  5. namespace Utils
  6. {
  7. //Extension class to provide serialize / deserialize methods to object.
  8. //src: http://stackoverflow.com/questions/1446547/how-to-convert-an-object-to-a-byte-array-in-c-sharp
  9. //NOTE: You need add [Serializable] attribute in your class to enable serialization
  10. public static class ObjectSerializationExtension
  11. {
  12. public static byte[] SerializeToByteArray(this object obj)
  13. {
  14. if (obj == null)
  15. {
  16. return null;
  17. }
  18. var bf = new BinaryFormatter();
  19. using (var ms = new MemoryStream())
  20. {
  21. bf.Serialize(ms, obj);
  22. return ms.ToArray();
  23. }
  24. }
  25. public static T Deserialize<T>(this byte[] byteArray) where T : class
  26. {
  27. if (byteArray == null)
  28. {
  29. return null;
  30. }
  31. using (var memStream = new MemoryStream())
  32. {
  33. var binForm = new BinaryFormatter();
  34. memStream.Write(byteArray, 0, byteArray.Length);
  35. memStream.Seek(0, SeekOrigin.Begin);
  36. var obj = (T)binForm.Deserialize(memStream);
  37. return obj;
  38. }
  39. }
  40. }
  41. }