Search Unity

Unity crashes when convert my own class object to default object

Discussion in 'Scripting' started by SweetMei25, May 24, 2019.

  1. SweetMei25

    SweetMei25

    Joined:
    Nov 17, 2018
    Posts:
    25
    Dear Professionals,

    Is it not possible to convert my own class object to object?
    So casting from VERSION to object...
    Please kindly review my code and let me know what's wrong here:

    Code (CSharp):
    1. public class VERSION
    2. {
    3.     public byte Major { get; set; } = 0x0;
    4.     public byte Minor { get; set; } = 0x0;
    5. }
    6.  
    7. public class MyClass: Monobehavior {
    8. void Start() {
    9. VERSION version = new VERSION();
    10. version.Major = 1;
    11. version.Minor = 0;
    12. byte[]  data = ObjectToByteArray(version); // Crashes here
    13. }
    14. private byte[] ObjectToByteArray(object obj)
    15.     {
    16.         if (obj == null)
    17.             return null;
    18.         BinaryFormatter bf = new BinaryFormatter();
    19.         using (MemoryStream ms = new MemoryStream())
    20.         {
    21.             bf.Serialize(ms, obj);
    22.             byte[] result = ms.ToArray();
    23.             return result;
    24.         }
    25.     }
    26. }
    27.  
    Regards
     
  2. Team2Studio

    Team2Studio

    Joined:
    Sep 23, 2015
    Posts:
    33
    Hi there,

    first of all, it's MonoBehaviour (with capital B), and you have to make your class Serializable to make it work. The following code works for me :

    Code (CSharp):
    1. using UnityEngine;
    2. using System;
    3. using System.IO;
    4. using System.Runtime.Serialization.Formatters.Binary;
    5.  
    6. [Serializable]
    7. public class VERSION
    8. {
    9.     public byte Major { get; set; } = 0x0;
    10.     public byte Minor { get; set; } = 0x0;
    11. }
    12.  
    13. public class MyClass : MonoBehaviour
    14. {
    15.     void Start()
    16.     {
    17.         VERSION version = new VERSION();
    18.         version.Major = 1;
    19.         version.Minor = 0;
    20.         byte[] data = ObjectToByteArray(version); // No longer crashes here
    21.     }
    22.  
    23.     byte[] ObjectToByteArray(object obj)
    24.     {
    25.         if (obj == null)
    26.             return null;
    27.         BinaryFormatter bf = new BinaryFormatter();
    28.         using (MemoryStream ms = new MemoryStream())
    29.         {
    30.             bf.Serialize(ms, obj);
    31.             byte[] result = ms.ToArray();
    32.             return result;
    33.         }
    34.     }
    35. }
    36.  
    Cheers,

    Bart
     
    SweetMei25 likes this.
  3. SweetMei25

    SweetMei25

    Joined:
    Nov 17, 2018
    Posts:
    25