Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

[SOLVED] Writing a custom LayoutGroup

Discussion in 'UGUI & TextMesh Pro' started by Oscaruzzo, Sep 7, 2015.

  1. Oscaruzzo


    Jan 26, 2015
    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 :)
  2. tomtu


    Jan 7, 2015
    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/
    Oscaruzzo likes this.
  3. Oscaruzzo


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

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    5. public class ForceAspect : MonoBehaviour {
    7.    LayoutElement layoutElement;
    8.    float width = 0.0f;
    10.    void Awake () {
    11.      layoutElement = GetComponent<LayoutElement>();
    12.    }
    14.    void OnRectTransformDimensionsChange() {
    15.      RectTransform rect = transform as RectTransform;
    16.      float newWidth = rect.sizeDelta.x;
    17.      if (newWidth != width) {
    18.        layoutElement.preferredHeight = newWidth;
    19.        width = newWidth;
    20.      }
    21.    }
    22. }