Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED] Writing a custom LayoutGroup

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

  1. Oscaruzzo

    Oscaruzzo

    Joined:
    Jan 26, 2015
    Posts:
    17
    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

    tomtu

    Joined:
    Jan 7, 2015
    Posts:
    2
    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

    Oscaruzzo

    Joined:
    Jan 26, 2015
    Posts:
    17
    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;
    4.  
    5. public class ForceAspect : MonoBehaviour {
    6.  
    7.    LayoutElement layoutElement;
    8.    float width = 0.0f;
    9.  
    10.    void Awake () {
    11.      layoutElement = GetComponent<LayoutElement>();
    12.    }
    13.  
    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. }