Dynamically created TextureRects don't stay centered inside in an HBoxContainer

Godot Version

4.5

Question

What it says in the title. I have the following nodes in the Control Node:


I dynamically create TextureRects with inside the NumberContainer in a function (it’s a damage number counter):

var number_textures = []

func _ready():
	for i in range(10):
		var texture = load("res://Assets/BattleUI/Numbers/spr_dmgnum_" \
		+ str(i) + ".png")
		number_textures.append(texture)

func display_damage(damage : int):
	for i in range(len(str(damage))):
		var number = TextureRect.new()
		number.set_indexed("modulate", Color.RED)
		
		number.texture = number_textures[int(str(damage)[i])]
		add_child(number)

When I add a number inside the HBoxContainer in the editor, it stays centered, however when I add the TextureRects during runtime, they are aligned left.

What’s interesting is that while trying to fix the issue, I tried to mess with the TextureRects using the Remote function, and if you turn the visibility off and on, the TextureRects become centered.

Any idea what could be causing this and how to fix it? Any help would be appreciated!

Maybe creating them at the same process cycle makes the container logic go mad.

Have you tried waiting for a frame inside the for loop for each loop?

1 Like

Interestingly enough, this wasn’t the issue, but I was able to figure out the problem thanks to this.

I set a timer inside the creation function, and was able to observe the numbers snapping to the left in real time. Looking through the code some more, I realized that during the number animation, which I call for after creating the numbers, I change the x position of the numbers to zero. I was able to fix this by only changing the y position in the animation.

Still, thanks for your reply!

1 Like