2
votes

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?

1
Sure it's possible. You would use Tilemap.SetTile. Then it's just a matter of mapping your binary file, the tiles, and your grid spacing all together. - ryeMoss
But I have an empty Grid, I need to first add layers (Tilemap objects) to it. That's what I don't know how to do :/ - Haytam
I believe the tilemap layers are nothing more than a gameobject with a TileMap and TileMapRenderer components on it. You can instantiate this and make it a child of the Grid. And then you just need to run the SetTile method on the appropriate Gameobject/tilemap. Haven't tested this but fairly certain that's how it'd work. - ryeMoss
And how would I instantiate a Gameobject, add TileMap/TileMapRenderer and make the Grid its parent please? - Haytam

1 Answers

2
votes

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;
}