How to add TileMap Layer in code only if the layer doesn't exist, how to loop through layers of a TileMap

Godot Version

4.3.dev2

Question

How can I interact with the layers of a TileMap in code?

For example, I want to loop through all the layers of the TileMap to see if the used cells of the layer contain the specified coords.
Or I want to place a cell in a specific layer without knowing if the TileMap has the layer.

There seems to be a property “layers” in the TileMap class but when I try to access it it says “Identifier “layers” not declared in the current scope”.

image

All of the snippets below do not work. What can I do instead?

for layer in layers:
	print(layer.name())
	
if not layers.has(index):
	add_layer(index)
	
for layer in layers:
	if get_used_cells(layer).has(coords):
		continue

TileMap does not have a layers property. Here’s how you can access them.

# They will always be ordered and start at zero, so you can start with:
for index in get_layers_count():
	# Then you can get the valid cells in the layer:
	var cells = get_used_cells(index)
	# And then you can check if the cell coordinates exist:
	var check_for = Vector2(69, 420)
	if check_for in cell:
		# Then do something.
		a_function_on_cell_in_layer(check_for, index)

If you want to check for the existence of a layer, you can do it by name using get_layer_name(index).

1 Like

Great, thank you!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.