Sorting nodes in the scene tree by a custom index

Godot Version

4.5

Question

I’m dynamically adding nodes to a VBoxContainer. The nodes have their own order variable. Since the order the nodes appear in a VBoxContainer are based on the order of the nodes in the scene tree, I need to make a function to sort all the children in VBoxContainer by their order variable. How would I do this?

You can use move_child to reorder children of the VBoxContainer

Can you be more specific? I know this function exists, but I don’t know how to utilize it to make a sorting function.

I figured it out, and it’s embarassing! :sparkling_heart:
I needed to call the move_child function while referencing the parent, instead of just by itself. For anyone who comes across this in the distant year of 2030 or something, here’s my code:

func sort_hero_list_in_container(container):
	for i in container.get_children():
		container.move_child(i, i.order)

i.order is referencing a variable that is assumed to exist in the child. Replace it with whatever you’d like to sort the children by. I hate my life, and I want to die.

1 Like