How to Handle Large Amounts of Unique Tiles with Tilemap?

Godot Version

4.4.1

Question

`I have a project that needs to be able to support a large amount of unique tiles, each having a separate image file. Basically it’s TileIMG-01, TileIMG-02, TileIMG-03, and so on. But none of the tiles have unique collisions or autotile properties. And it’d be nice to have support for custom tiles too, which means having to put each one manually into a tilemap with different properties doesn’t really work for me. Or it’d just be really impractical.

Essentially, how would I go about having the tilemaps be created at runtime or use the same base as a template tile? It’d be like, I call a function to place say dirt, and it uses the Img-ID of Dirt so it can place auto-tiling dirt tiles with the same collision/auto-tiling properties of the template tile at runtime, and be able to do this for many tiles, without ever having to put them in manually.`

If you’re using 4.4.1 then you should use TileMapLayer instead of TileMap since TileMap has been deprecated. Anyway, it’s a bit complicated to create tiles in code.

TileMapLayers have all their tile data stored in the TileSet resource. So in order to place the tiles in the TileMapLayer you’ll need to add them to the TileSet through code as well. You can use the TileSet.add_source() function to do that. It takes in a TileSetSource as an argument, and since you’re using images, you should make a TileSetAtlasSource specifically. Use the TileSetAtlasSource.create_tile() function to make the tiles. Since you only have one image per tile, the coordinates will all be Vector2i(0, 0).

Since you have a lot of images as well, you probably want to look through the directory to find them instead of writing them down in a list. Since the image files can’t be found with DirAccess after export, you should use ResourceLoader.list_directory() in order to list all the image files and load them so you can make tiles with them.

After you have made all the tiles, you need to store all the source ids of the tiles too so you can use the TileMapLayer.set_cell() function to place down the tiles.

It’s a lot of code. It might be easier to use an external image editor to put all the tiles into a single image file that you can put into the tileset as one source id and auto-create the tiles for.