Serialization Surrogate

A binary serialization formatter helper for Unity

Serialization Surrogate is setting of binary serializer and deserializer.

Unity provides many useful data model but not natively serializable to binary. Following types are included in this library.

  • AnimationCurve

  • Bounds

  • BoundsInt

  • Color

  • Gradient

  • Hash128

  • LayerMask

  • Matrix4x4

  • Quaternion

  • RectInt

  • Rect

  • Vector2

  • Vector2Int

  • Vector3

  • Vector3Int

  • Vector4

[System.Serializable]
public class PlayerData
{
    public string playerName;
    public int score;
    public Vector3 position;

    public PlayerData(string name, int score, Vector3 pos)
    {
        playerName = name;
        this.score = score;
        position = pos;
    }
}

public class SerializationExample : MonoBehaviour
{
    private string filePath;

    void Start()
    {
        filePath = Application.persistentDataPath + "/playerData.dat";

        PlayerData data = new PlayerData("John", 100, new Vector3(1, 2, 3));

        SerializeData(data);

        PlayerData loadedData = DeserializeData();

        if (loadedData != null)
        {
            Debug.Log("Loaded Player Name: " + loadedData.playerName);
            Debug.Log("Loaded Score: " + loadedData.score);
            Debug.Log("Loaded Position: " + loadedData.position);
        }
    }

    void SerializeData(PlayerData data)
    {
        IFormatter formatter = GetBinaryFormatter();
        using (FileStream stream = new FileStream(filePath, FileMode.Create))
        {
            formatter.Serialize(stream, data);
        }
        Debug.Log("Data serialized to " + filePath);
    }

    PlayerData DeserializeData()
    {
        if (File.Exists(filePath))
        {
            IFormatter formatter = GetBinaryFormatter();
            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                return formatter.Deserialize(stream) as PlayerData;
            }
        }
        else
        {
            Debug.LogWarning("Save file not found in " + filePath);
            return null;
        }
    }

    private IFormatter GetBinaryFormatter()
    {
        BinaryFormatter formatter = new();
        SurrogateSelector selector = new();
        Vector3SerializationSurrogate vector3Surrogate = new();

        selector.AddSurrogate(
            typeof(Vector3), 
            new StreamingContext(StreamingContextStates.All), 
            vector3Surrogate
        );
        formatter.SurrogateSelector = selector;

        return formatter;
    }
}

Last updated