What happens if I sort a list of objects (for example Area2D-Objects)?

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

If I add objects to an empty array. According to which property are they sorted?

var test = [$Area2D, $Area2D_2, $Area2D_3, $Area2D_4, $Area2D_5]
print(test)
test.sort()
print(test)

In any case, the order changes after sorting…

:bust_in_silhouette: Reply From: PrecisionRender

Arrays (a.k.a. lists) are sorted alphabetically when using the array.sort() function. But NodePaths, like what you have in your test array, are not treated as text. When they are sorted, it uses the unique object ID of the node your path is leading to. So if Area2D_3 has an ID number larger than Area2D_5, then Area2D_5 will be put before Area2D_3 in your array.

To fix this, I recommend using strings instead of NodePaths for sorting this array, then using get_node():

var test = ["Area2D_1", "Area2D_2", "Area2D_3", "Area2D_4", "Area2D_5"]
print(test)
test.sort()
print(test)
for area in test:
	print(get_node(area))

Out of curiosity, how does one access said ID? I tried running OP’s code with a bunch of random nodes, and this is what I got:

(unsorted)
[[Particles2D:1201], [Node2D:1202], [AnimatedSprite:1206], [AnimationPlayer:1203], [AudioStreamPlayer:1204], [Bone2D:1205]]

(sorted)
[[Particles2D:1201], [AnimationPlayer:1203], [Node2D:1202], [Bone2D:1205], [AnimatedSprite:1206], [AudioStreamPlayer:1204]]

So apparently they are not sorted according to RID. The Node.get_index() has a different meaning - and might be useful in OP’s case. I tried looking into the source but I can’t seem to find any mention of “operator <” in either Node or Object classes.

skysphr | 2021-09-28 17:49

Yeah, there is something sort, but not the name or the id of the objects…

Lebostein | 2021-09-28 17:57