Help with convert Class to Byte[]

Hi i´m try to convert a class :

using UnityEngine;
using System.Collections;

public class SendInfo
{
    public int name = 0; //0 Pj;
    public string ship;
    public Vector3 posPj;
    public int wp;
    public int add;
}

to Byte[ ] . But y get this error :

10-20 23:08:09.612: I/Unity(25553): at System.Xml.Serialization.XmlSerializer.Serialize (System.Xml.XmlWriter writer, System.Object o, System.Xml.Serialization.XmlSerializerNames
10-20 23:08:09.632: I/Unity(25553): InvalidOperationException: The type of the argument object ‘System.Xml.Serialization.XmlSerializer’ is not primitive.

My code here:

void SendMessagePjMp ()
    {
        byte[] message;
        using (MemoryStream stream = new MemoryStream())
        {
            XmlSerializer x = new XmlSerializer(typeof(SendInfo));
            x.Serialize (stream,x);
            message = stream.ToArray ();
        }
        PlayGamesPlatform.Instance.RealTime.SendMessage(false, idP2.ParticipantId, message);
    }
public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
    {
        XmlSerializer x = new XmlSerializer (typeof(SendInfo));
        using (MemoryStream stream = new MemoryStream(data))
        {
            sendInfoPj2 =  (SendInfo) x.Deserialize (stream);
        }
        if(sendInfoPj2.name == 0)
        {
            posPj2 = sendInfoPj2.posPj;
            ship2 = sendInfoPj2.ship;
            wp2 = sendInfoPj2.wp;
            add2 = sendInfoPj2.add;
        }
    }
x.Serialize(stream,x);

You just passed the XmlSerializer in to the Serialize method of XmlSerializer.

That would serialize itself.

You should be passing in the SendInfo object.

1 Like

Thanks you very much ¡¡ This works :slight_smile:

x.Serialize(stream, SendInfo);