Search Unity

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

Discussion in 'Editor & General Support' started by XenonSpher, Dec 19, 2016.

  1. XenonSpher

    XenonSpher

    Joined:
    Dec 11, 2015
    Posts:
    29
    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()
     
  2. DWit

    DWit

    Joined:
    Dec 4, 2016
    Posts:
    23
    You want to sort it by name in UI? Just add SetSiblingIndex after each sort (above you've sorted objects just in array).

    Code (csharp):
    1.  
    2. GameObject[] count = GameObject.FindGameObjectsWithTag("ValuePrefab");
    3. GameObject[] countOrdered = count.OrderBy(go => go.name).ToArray();
    4. for (int i = 0; i < countOrdered.Length; i++)
    5. {
    6.    countOrdered[i].transform.SetSiblingIndex(i);
    7. }
    8.  
     
  3. XenonSpher

    XenonSpher

    Joined:
    Dec 11, 2015
    Posts:
    29

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

    Code (csharp):
    1.  
    2. GameObject[] countOrdered =count.OrderBy(go => go.name).ToArray();
    3.  
    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!!
     
  4. Ryalin

    Ryalin

    Joined:
    Apr 25, 2019
    Posts:
    1
    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 :)
     
unityunity