Serializing Data

Learn how to use helper functions to serialize data for IMultipeerNetworking.

Serialization Helpers

Sending data over a MultipeerNetworking (or ARNetworking) object requires it to be a byte[]. To make using the API easier, ARDK provides utility scripts to help serialize commonly used object types into byte[] to be passed over the network, then deserialize them upon arrival.

For example, a Vector3 :

using System.IO;
using Niantic.ARDK.Utilities.BinarySerialization;

private static byte[] SerializeVector3(Vector3 vector)
{
  using (var stream = new MemoryStream())
  {
    GlobalSerializer.Serialize(stream, vector);
    return stream.ToArray();
  }
}
using System.IO;
using Niantic.ARDK.Utilities.BinarySerialization;

private static Vector3 DeserializeVector3(byte[] data)
{
  using (var stream = new MemoryStream(bytes))
    return (Vector3)GlobalSerializer.Deserialize(stream);
}

Multiple fields/objects can be serialized into a single byte[] by a BinarySerializer :

using System.IO;
using Niantic.ARDK.Utilities.BinarySerialization;

private static byte[] SerializePositionAndRotation(Vector3 position, Vector3 rotation)
{
  using (var stream = new MemoryStream())
  {
    using (var serializer = new BinarySerializer(stream))
    {
      serializer.Serialize(position);
      serializer.Serialize(rotation);
      // here any other object can be serialized.
      return stream.ToArray();
    }
  }
}
using System.IO;
using Niantic.ARDK.Utilities.BinarySerialization;

private static Vector3[] DeserializePositionAndRotation(byte[] data)
{
  using (var stream = new MemoryStream(data))
  {
    using (var deserializer = new BinaryDeserializer(stream))
    {
      var result = new Vector3[2];
      result[0] = (Vector3)deserializer.Deserialize(); // position
      result[1] = (Vector3)deserializer.Deserialize(); // rotation
      // The number and order of the Deserialize() calls should match the Serialize() calls.
      return result;
    }
  }
}

See Also

Low level networking

The high level networking API (Hlapi)