- Home /
Sorting the children of a Grid Layout in 4.6 UI
Hi. So I'm making a quest log. Once I quest is started, I need to add it to the active section of the quest log, which is a Grid Layout. The only problem is, this adds it at the bottom of the list. I want it to be added to the top so the most recent quests appear first. How can I arrange the elements of the grid layout through script? Thanks.
Answer by chilemanga · Dec 21, 2017 at 02:27 PM
There's a solution that's better performant than de-parenting the UI elements and then parenting them again in the required order, which is using the SetSibling methods from the Transform.
SetAsFirstSibling: Move the transform to the start of the local transform list. SetAsLastSibling: Move the transform to the end of the local transform list. SetSiblingIndex: Sets the sibling index. https://docs.unity3d.com/ScriptReference/Transform.html
So, in your case, when a quest becomes active you just need to set that quest object as the first sibling. You can find more info in this thread: https://forum.unity.com/threads/order-of-elements-in-layout-groups.267668/
This should be the answer. You can make a sorting worker function with these to get the desired behavior.
Answer by DoomSamurai · Dec 04, 2014 at 12:15 AM
You need to de-parent your ui elements, sort them (in a List or Array) and then re-parent them to the GridLayout transform in the sorted order. Remember that for UI elements you need to use Transform.SetParent to set the parenting.
This is a good solution, but there's some set sibling methods that performs better and will avoid to lose some FPS. Please, check my answer below.
Answer by orb · Sep 14, 2014 at 08:14 PM
It depends on what the object holding the list of quests is, but if it's just a plain List why not simply use list.Insert(0, item) when you add it to put it first?