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!

Transform.SetSiblingIndex(int) and Transform.GetSiblingIndex()

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*).SetSiblingIndex(i);*

}

  • }*
    }

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);
    }
}