I am trying to serialize a custom class into a byte[] array using BinaryFormatter, upload it to steam using the steam-api, download it again later and deserialize it back into the custom class. The steam part is already working but when I deserialize the byte[] 90% of the time I receive a SerializationException "end of stream encountered before parsing was completed" or it actually creates the instance of the class but the values are all wrong.
10% of the time is works fine though, not sure why it works sometimes but not most of the time.
The class in question
[Serializable]
public class ReplayEntry
{
public List<SerializableVector3> Position;
public List<SerializableVector3> Rotation;
public List<SerializableVector3> Velocity;
public float Offset;
public UGCHandle_t handle;
\\... Constructors below
}
Serialization:
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
ms.Flush();
return ms.ToArray();
}
}
Deserialization:
public static Object ByteArrayToObject(byte[] arrBytes)
{
using (MemoryStream memStream = new MemoryStream(arrBytes))
{
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return obj;
}
}
The 'SerializeableVector3' type is because Unity's vector3 is not serializeable
[Serializable]
public struct SerializableVector3
{
public float x;
public float y;
public float z;
public SerializableVector3(float rX, float rY, float rZ)
{
x = rX;
y = rY;
z = rZ;
}
public static implicit operator Vector3(SerializableVector3 rValue)
{
return new Vector3(rValue.x, rValue.y, rValue.z);
}
public static implicit operator SerializableVector3(Vector3 rValue)
{
return new SerializableVector3(rValue.x, rValue.y, rValue.z);
}
}