Home > Mobile >  Unity Vertical Layout Group height not calculating off children
Unity Vertical Layout Group height not calculating off children

Time:10-29

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?

CodePudding user response:

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

  • Related