[SOLVED] Writing a custom LayoutGroup

Hi, I’m trying to implement this kind of layout: I have a vertical rectangle (height is greater than width). This rectangle should contain two non-overlapping children, one on the bottom and one on the top.

The bottom one should be a square: it’s width is the same as the parent’s (and, being a square, it’s height should also be the same).

The top one should fill all the remaining space in the parent.

That’s it.

I can’t find a way to get this result with LayoutElement, VerticalLayoutGroup, AspectRatioFitter, etc (but if anyone can succeed in that, I’m interested in learning how) so I’m trying to implement a custom LayoutGroup.

Sadly the docs are quite terse on this and I can’t find any example. Any hints?

Thaks :slight_smile:

Hey Oscaruzzo,

You could achieve this using vertical layout group and having children with Layout Element attached. The top one should have flexible height of 1 and the bottom one flexible height of 0 and preferred Height set (equal to container’s width from what you said I guess) so that it takes the amount of space that you want. If width was dynamic you’d you’d need to update bottom container’s height from code so it keeps the square ratio - don’t think the aspect ratio fitter would work here but using one with width driving the height could work maybe? Set vertical layout group to NOT expand the height of the children which will cause the remaining vertical space will be distributed at 1:0 ratio (as set with flexible heights) between the children so all the remaining space will be taken by the top container.

hope it helps o/

1 Like

Thanks, it worked with your suggestion and adding a script like this

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ForceAspect : MonoBehaviour {

   LayoutElement layoutElement;
   float width = 0.0f;

   void Awake () {
     layoutElement = GetComponent<LayoutElement>();
   }
  
   void OnRectTransformDimensionsChange() {
     RectTransform rect = transform as RectTransform;
     float newWidth = rect.sizeDelta.x;
     if (newWidth != width) {
       layoutElement.preferredHeight = newWidth;
       width = newWidth;
     }
   }
}