- Home /
Re-order Horizontal Layout Group at Runtime?
Hi all,
Does anyone know how to re-order the children of a Horizontal Layout Group at Runtime?
Essentially I want to allow users to re-order buttons which are contained in a horizontal layout group.
Thanks for your time!
Answer by tigertrussell · Mar 21, 2015 at 04:53 PM
Transform.SetSiblingIndex(int)
and Transform.GetSiblingIndex()
Wanted to add a comment in case others stumble upon my same issue.
This will not work if you're trying to move prefab objects around (accidentally) and it will fail without warning. Remember to instantiate your prefabs before trying this!
Answer by BUWbrean · Jan 04, 2018 at 12:48 PM
Thank you very much for sharing your finding. I had to write a small script that ensures the order because every time I run my code the order changes (I think this might be a bug in Unity)
using System.Collections.Generic;
using UnityEngine;
public class ForceButtonOrder : MonoBehaviour {
[Tooltip("list of button names")]
public List<string> order;
// Use this for initialization
void Start () {
for (int i = 0; i < order.Count; i++)
{
transform.Find(order[i]).SetSiblingIndex(i);
}
}
}
Answer by Fattie · Oct 08, 2020 at 11:59 AM
Yes, it's a ridiculous Unity bug.
Even if you are NOT reordering them at RUNTIME, horizontal layout groups sometimes screw the order of elements - so, they get changed from the order seen in the scene in the Editor.
In this simple example I had to just force all elements (there were four) to bne in the right place, doing so at Start() time seems to work. Nice spot by @BUWbrean
using UnityEngine;
public class BizarreGroupFixer : MonoBehaviour
{
// fix absurd Unity bug, which screws the ordering of
// horizontal groups (perhaps if one is a prefab?)
public Transform a;
public Transform b;
public Transform c;
public Transform d;
void Start()
{
a.SetSiblingIndex(0);
b.SetSiblingIndex(1);
c.SetSiblingIndex(2);
d.SetSiblingIndex(3);
}
}