How can I sort the children of a node?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Drawsi

I know there’s sort() but it works only on arrays although it doesn’t do anything to the x.get_children() array. I can’t seem to make the nodes sort at all, only other arrays.

Example of nodes printed:
[1:<Node2D#37429970509>, 3:<Node2D#81788931609>, 2:<Node2D#84540395243>, 5:<Node2D#96955535787>, 4:<Node2D#101049176678>]

I’d like to have them as:
[1:<Node2D#37429970509>, 2:<Node2D#84540395243>, 3:<Node2D#81788931609>, 4:<Node2D#101049176678>, 5:<Node2D#96955535787>]

:bust_in_silhouette: Reply From: Joel Gomes da Silva

In a scene like this:

┖╴Node
    ┠╴3
    ┠╴5
    ┠╴1
    ┠╴4
    ┖╴2

You can use the following code:

var sorted_nodes := get_children()

sorted_nodes.sort_custom(
	# For descending order use > 0
	func(a: Node, b: Node): return a.name.naturalnocasecmp_to(b.name) < 0
)

for node in get_children():
	remove_child(node)

for node in sorted_nodes:
	add_child(node)

And the result children order will be the following:

 ┖╴Node
    ┠╴1
    ┠╴2
    ┠╴3
    ┠╴4
    ┖╴5

There’s also Node.move_child to reorder children without removing and readding them to the parent, but I think this solution may work well.

I tried my best to understand the code but I don’t get it so far.
It works perfectly tho.
Many thanks, you have saved me many hours of painful trials and errors.

Drawsi | 2023-04-05 11:28

edit: as I posted this I realised I misread Joel’s comment about this existing… oops

Actually for anyone finding this in the future, there does seem to be a move_child since Godot 4.0.

Node — Godot Engine (4.0) documentation in English

alexdlm | 2023-04-30 08:23