Haytam
Haytam

Reputation: 4733

How to programmatically add Tilemaps to a Grid

I am new to Unity3d and I'm trying to make my first 2d game.
In order to create Tilemaps in Unity, we usually right-click then choose 2D Object > Tilemap, which gives us a Grid + Tilemap, each child tilemap in that grid is considered a layer.

What I want is to be able to generate/add tilemaps with a script to an empty Grid (everytime empty the Grid then add layers).

I want to make a map system where the map is generated using binary files every time the player changes the map.

Is that possible?

Upvotes: 2

Views: 4665

Answers (1)

Haytam
Haytam

Reputation: 4733

Thanks to @ryeMoss, I ended up doing the following:

private Tilemap CreateTilemap(string tilemapName)
{
    var go = new GameObject(tilemapName);
    var tm = go.AddComponent<Tilemap>();
    var tr = go.AddComponent<TilemapRenderer>();

    tm.tileAnchor = new Vector3(AnchorX, AnchorY, 0);
    go.transform.SetParent(_mapGrid.transform);
    tr.sortingLayerName = "Main";

    return tm;
}

Upvotes: 2

Related Questions