How to programatically add animated tiles to TileSet?

Godot Version

4.4

Question

I have plenty of animated tiles, and I expect to do updates frequently to many tiles, so I’m looking for a way to automate adding all tiles into my tileset every time I make some changes. I managed to do that for static tiles already, but I can’t get animated tiles to work. I get out of bounds errors, and many other things. The textures I’m importing are PNG spritesheet.

Here’s what I tried in my tool script attached to TileMapLayer node:

func create_animated_tile_source(tile_name: String, texture: Texture2D) -> void:
	var source = TileSetAtlasSource.new()
	source.texture = texture
	source.texture_region_size = Vector2i(50, 50)
	source.resource_name = tile_name

	# Add source to TileSet FIRST
	tile_set.add_source(source)

	var anim_data = animated_tiles[tile_name]
	var base_coord = Vector2i(0, 0)
	source.create_tile(base_coord)

	# Configure animation parameters AFTER adding the source
	source.set_tile_animation_columns(base_coord, anim_data["h_frames"])
	source.set_tile_animation_frames_count(base_coord, anim_data["frame_count"])
	source.set_tile_animation_speed(base_coord, anim_data["fps"])

	# Apply collision data
	var tile_data = source.get_tile_data(base_coord, 0)
	var collision_id = collision_types.get(tile_name, 0)
	apply_collision_shape(tile_data, collision_id)

	print("Added animated tile:", tile_name)

Update: This new code correctly applies fps (speed), frame columns, collision shape and tile name. The problem remaining: it only adds one frame (first frame) of the spritesheet. I can’t find a method for adding frames. It also appears to be removing the entire spritesheet from source, as if only that one frame existed so even if I wanted to add frames manually I couldn’t.

Update 2: I am also getting this error for the animated tiles:

ERROR: Cannot set animation columns count, tiles are already present in the space the tile would cover.

Update 3: This code actually worked all along, the texture I was passing was from a wrong directory on accident.