3

I feel like I am not understanding the Vertical Layout Group component in Unity 2020.3.21 and I am hoping that someone can explain what I am missing.

I have a series of runtime-controlled UI components that I want displayed vertically top-to-bottom. I need to be able to toggle these components on and off at run-time, and have the parent Vertical Layout Group size automatically update to the height of all of the active children. This is exactly the sort of thing the Vertical Layout Group is supposed to handle, right?

When I build out a simple example, I am seeing that the Vertical Layout Group correctly positions the children in a vertical list. However, it competely ignores the sizes of the children when measuring it's own height. This is a problem because I want to be able to throw this container in a Scroll View -- if the height is not accurate, then the Scroll View doesn't work properly.

Here's my demo. I have a series of children in a VLG that all have explicit set heights in their RectTransform. All of them are direct children of the VLG. None of them use a LayoutElement; all heights are explicitly defined in a RectTransform. Here's the scene hierarchy, with the compile-time RectTransform heights of each component in parenthesis.

Canvas (325x812)
  GameObject (812)
    Vertical Layout Group (100)
      Text (45)
      Spacer (100)
      Text Input (48)
      Spacer (20)
      Button (48)

Here are my VLG settings:

enter image description here

When I run the game, I can see the outline of each UI object in the Scene tab. The children clearly have their heights set. Yet the VLG still has it's static compile-time height of 100 instead of the sum of the child heights.

Am I missing something about how the Vertical Layout Group works? How can I get this VLG to have it's Height property set to the actual total height of it's active children at runtime?

1 Answer 1

9

ContentSizeFitter with Vertical Fit set to preferred size should do the trick. I did a quick test using simplified structure based on your example and got height calculated correctly (height of children objects is 100+50+75):

Test example

2
  • Oh interesting. The Vertical Layout Group doesn't re-calculate the size on it's own? It needs this extra behavior added to re-calculate? But yep, I can confirm this does what I want it to! Thank you!
    – BU0
    Commented Oct 28, 2021 at 19:36
  • Glad it helped! That's the approach I've seen in a few commercial Unity games. I think the idea is that children gameobjects are not usually supposed to control the parent's transform, so it requires a separate component that is made specifically to break this rule, leaving no room for accidental usage.
    – BFyre
    Commented Oct 29, 2021 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.