Search Unity

trying to serialize a struct, any ideas?

Discussion in 'Scripting' started by Quadgnim, Jan 27, 2014.

  1. Quadgnim

    Quadgnim

    Joined:
    Sep 10, 2012
    Posts:
    132
    Hi all,

    I'm trying to serialize a struct for purposes of sending it as a list through an RPC. I have it working great if it's a type string, but as soon as I change it to a struct that includes int, string, vector, etc.. it fails.

    The failure is on the:

    binf.Serialize( mems, testobjarray);

    with the error:

    Vector3 is not marked as Serializable


    I've marked the class as serializable and the struct as serializable. Before I continue down a rats nest, can someone confirm if it's even possible to serialize a struct, and if so what's the trick to it?

    Sample Code:


    [System.Serializable]
    internal struct State
    {
    internal float timestamp;
    internal Vector3 pos;
    internal Vector3 velocity;
    internal Quaternion rot;
    internal int objid;
    }


    void SomeFunctionThatWillSendAnRPC()
    {
    List<State> testobjlist = new List<State>();
    State testobj = new State();
    testobj.objid = 555;
    testobjlist.Add(testobj);


    BinaryFormatter binf = new BinaryFormatter();
    MemoryStream mems = new MemoryStream();
    binf.Serialize( mems, testobjlist);

    networkView.RPC( "RemoteAvatarBatchUpdate", RPCMode.Others, mems.GetBuffer() );

    }


    Any help is greatly appreciated.
     
  2. G_K

    G_K

    Joined:
    Jan 12, 2014
    Posts:
    6
  3. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    As far as I remember, Unity is unable to serialize structs. Why don't you try with a class instead?
     
  4. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Well if these are for messages being sent through RPC... and you're doing a lot of them... using a class means more allocation / garbage collection.

    For something simple like you're doing I'd recommend looking at something like JsonObject in the asset store (it's free).
     
  5. Quadgnim

    Quadgnim

    Joined:
    Sep 10, 2012
    Posts:
    132
    Thanks guys. I'll look into both. Maybe the trick is to store 3 floats instead of the full Vector3. Might be the quickest fix here.