Can you determine if a Custom Data Layer exists for a TileMapLayer?

Godot Version

4.3

Question

Is there a way to check if a custom data layer exists in a TileMapLayer before trying to get the value?

I’ve setup custom data layers to do seasonal swapping of tiles in a TileMapLayer. The code works fine, but I didn’t set a custom data layer for summer tiles that don’t have it (i.e. winter if the only different tile). I wanted to just handle the null myself. I can’t seem to find a way to check if the layer exists.

I’m getting this error, and while it doesn’t stop execution, I like to deal with all warnings and errors.

E 0:00:04:0926   village.gd:307 @ get_seasonal_tile(): TileSet has no layer with name: summer_offset
  <C++ Error>    Condition "p_layer_id < 0" is true. Returning: Variant()
  <C++ Source>   scene/resources/2d/tile_set.cpp:6530 @ get_custom_data()
  <Stack Trace>  village.gd:307 @ get_seasonal_tile()
                 village.gd:335 @ summerize()
                 village.gd:294 @ summer_wind_blow()
                 main.gd:19 @ _input()

This is the code that is executing.

## Returns Vector2i of tile if it exists, or Vector2i(-1,-1) if it doesn't
func get_seasonal_tile(tile_position: Vector2i, original_atlas_coords: Vector2i, tile_map_layer: TileMapLayer, season: String):
	var tile_data: TileData = tile_map_layer.get_cell_tile_data(tile_position)
	if tile_data:
		var offset = tile_data.get_custom_data(season)
		if offset:
			return original_atlas_coords + offset
	return Vector2i(-1,-1)
1 Like

So creating the data layer without any data in it solved the problem. Not the most elegant solution. I’m wondering if anyone else has any ideas.

1 Like

I have the same problem and couldn’t find an elegant solution yet.

It can be checked in the TileSet object attached to the TileMap/TileMapLayer. It doesn’t have a method to directly check that the layer exists but you can iterate over all the layers to find it. The methods to use are get_custom_data_layers_count() and get_custom_data_layer_name().

1 Like

I’m late to the party, but theres a function in the tileset called get_custom_data_layer_by_name which returns -1 if it doesnt exist

3 Likes

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