Skip to content

Instantly share code, notes, and snippets.

@Deepscorn
Last active May 21, 2022 12:12
Show Gist options
  • Save Deepscorn/1321fde46659b128ddb4 to your computer and use it in GitHub Desktop.
Save Deepscorn/1321fde46659b128ddb4 to your computer and use it in GitHub Desktop.
using UnityEngine;
// Solves problem: HorizontalLayoutGroup successfully alignes children which present as it's children no matter visible they are or not.
// Visibility is controlled by Canvas Group's alpha value. That script just removes child from children list when alpha is 0. So that visible
// elements are aligned properly without gap
public class HorizontalLayoutGroupHelper : MonoBehaviour {
private CanvasGroup[] children;
private int[] siblingIndexes;
private Transform parentTransform;
void Awake () {
children = GetComponentsInChildren<CanvasGroup>();
siblingIndexes = new int[children.Length];
for (int i = 0; i < siblingIndexes.Length; ++i)
{
siblingIndexes[i] = children[i].transform.GetSiblingIndex();
}
parentTransform = transform.parent;
}
void Update () {
for (int i = 0; i < siblingIndexes.Length; ++i)
{
var child = children[i];
if (Mathf.Approximately(child.alpha, 0F))
{
if (child.transform.parent != parentTransform)
{
child.transform.SetParent(parentTransform);
}
}
else if (child.transform.parent != transform)
{
child.transform.SetParent(transform);
child.transform.SetSiblingIndex(siblingIndexes[i]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment