About sort_custom(), Arrays

Godot Version

4.5.1 Stable

Question

So my question is two-pronged, first I will explain what I want here.

I have an array based on a node tree;

var arraylist : Array = []

func _ready() -> void:
	arraylist = node.get_children()

I’m ok with sharing references btw, my intention is to re-sort the children but in a very particular way.

I want to take an object at a selected index and move it to another index, offsetting the objects in between.
For example: if my array has a size of 5, and I’m selecting index 3, I’d like the object at index 3 to move to index 1 (not 0), with the old objects in indexes 1 and 2, now shift to 2 and 3 respectively.

I guess my first question is “is this even possible”?
I looked up plenty YT videos on arrays and array commands, but it seems like every godot YTer copy from each other when explaining sort_custom(). Every example I’ve seen is the same array of typed in item names and rarity, and they showcase sort_custom() by showing a func that sorts by rarity and/or name. I’m not adept at gdscript enough (yet) to really grasp the depth or lack thereof of sort_custom(), hence the next question-

What else can sort_custom() do?

Would it be possible to sort my array the way I want using sort_custom() and creating a func that allows for this? I have made attempts, but I keep getting hung up on arrays not allowing an object to freely move indexes without changing the size.

I tried emulating movement with push and pop commands, but while I can pop_at() a specific index, I can’t push at a specific index (or if you can then I overlooked it/can’t find it).

Any suggestions?

You can “push at” with .insert

What’s the purpose of all this? Describe the problem you’re ultimately trying to solve. Maybe array isn’t the right data structure for it.

1 Like

My problem is exactly what I typed, I don’t know how to describe it any better. If you’re asking what am I trying to use this for, two things:

I am prototyping a weapon select system. For the record, it works fine, I set up an array to cycle between any number of weapons I may add. Right now, the weapons are child nodes to a bone attachment. This is why the array is based off of node.get_children()

Right now, it swaps between 4 nodes, an empty-handed blank mesh (Gun0), and 3 different weapon meshes. In practical terms

Selection is toggled by visibility, it all works.

What I’m trying to do is create a qol change to the system. Whereas no matter what Gun you select, you can always select none by pressing left, for example.

2nd, I’d like to match this up with a visual representation via UI Control nodes. As of this moment, I haven’t done much work on that because I’m trying to design a custom scroll container first, but I imagine similar sorting would be required.

This doesn’t look like an array sorting problem. Simply use Node::move_child()

2 Likes