The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

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...

in Engine by (66 points)

1 Answer

0 votes

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))
by (125 points)

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.

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.