how do I arrange childrens in heirarchy in order using <RectTransform>().SetSiblingIndex()w

I have this children inside a canvas(its a UI) that I could instantiate up to 7 by clicking this ui buttons it has a tag of ValuePrefab

[1] Instatiate UI box 1 that has a unique purpose
[2] Instatiate UI box 2 that has a unique purpose
[3] Instatiate UI box 3 that has a unique purpose
[4] Instatiate UI box 4 that has a unique purpose
[5] Instatiate UI box 5 that has a unique purpose
[6] Instatiate UI box 6 that has a unique purpose
[7] Instatiate UI box 7 that has a unique purpose

for example I’ll click 1,4,6

this will display 3 unique UI boxes vertically by using a Vertical Layout Group and corresponds the order of my click.

now what if I click 1,6,4 this would display first the 1 ui box, and then the 6 and then the 4. I want it in order.

Ive been researching on it and thought that .SetSibingIndex() or SetAsFirstIndex or SetAsLastIndex is the proper way of doing so, but the problem is I don’t know how to create this on script… also I’ve research about using System.Linq is an ok approach to… but again I cant seem to make this work.

GameObject[ ] count = GameObject.FindGameObjectsWithTag(“ValuePrefab”);

count.OrderBy(go => go.name).ToArray()

You want to sort it by name in UI? Just add SetSiblingIndex after each sort (above you’ve sorted objects just in array).

GameObject[] count = GameObject.FindGameObjectsWithTag("ValuePrefab");
GameObject[] countOrdered = count.OrderBy(go => go.name).ToArray();
for (int i = 0; i < countOrdered.Length; i++)
{
   countOrdered[i].transform.SetSiblingIndex(i);
}
8 Likes

OH MY GOD THANK YOU!!! SO ALL I NEEDED WAS A FORLOOP IVE BEEN USING THE SCRIPT

GameObject[] countOrdered =count.OrderBy(go => go.name).ToArray();

already… so I needed was to apply them. hahaha… but seriously none of the topics that I’ve read didn’t put a forloop… THANKS SO MUCH!!

This worked for me too, however, I really want to achieve this sorting to occur every frame, and for some reason I can’t make that happen. (I’m making something akin to Recount, or an MMORPG DPS meter that needs to change dynamically every frame based on who is in pole position). If you know how, I’d be most grateful :slight_smile:

1 Like