How to use binaryformatter with custom class in unity?

I had a serializable class which had a TileBase and a Matrix4x4 variable in it. I wanted to save it as a custom binary file using bf.serialize() it but it always said “SerializationException: Type ‘UnityEngine.Tilemaps.TileBase’ in Assembly ‘UnityEngine.TilemapModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null’ is not marked as serializable.” Here is my code:

This is my serializable class:

[Serializable]
public class SerializableTile
{
    public TileBase tile;
    public Matrix4x4 rotation;

    public SerializableTile(TileBase _tile, Matrix4x4 _rotation)
    {
        tile = _tile;
        rotation = _rotation;
    }
}

This is my save method:

public static void SaveRoom(SerializableTile _tiles, string _roomName)
    {
        BinaryFormatter formatter = new BinaryFormatter();

        string _path = Path.Combine(path, _roomName);

        using (FileStream stream = new FileStream(_path, FileMode.Create))
        {
            formatter.Serialize(stream, _tiles);
        }
    }

@Long2904 in a Script Serialization documentation there’s a note about Custom Serialization.
The link below has an example on how to implement an interface ISerializationCallbackReceiver which would allow you to handle data before/after serialization. This way you could wrap the data of your TileBase in a type that can be serialized and in OnAfterDeserialize() create a new instance of it using that data.

Script Serilization