- Home /
Question regarding VerticalLayout - list is not populating correctly except during Start()!
Hello! I am currently working on a project to make a dynamic inventory screen. The inventory needs to populate a list of items at runtime based on clicking a tab for that type of item (weapons, armor, etc.) I am using a ScrollView with a vertical layout to fit the items as described in the tutorial here: https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/creating-scroll-lists-at-run-time
I followed it and everything worked great! I use the following function to populate the list
void PopulateList(List<Item> items)
{
foreach(Item item in items)
{
// Create the list item in gamespace
GameObject list_item = Instantiate(inventory_list_item) as GameObject;
list_item.transform.SetParent(contentPanel.transform, false); // child it to the panel object that we will populate the ScrollView with.
List_Item itemScript = list_item.GetComponent<List_Item>();
// Send it a reference to the item that it represents
itemScript.BuildListItem(item);
// We want the item to register click events.
list_item.GetComponent<Button>().onClick.AddListener(delegate { InvItemIsClicked(itemScript); });
}
inventoryUpdated = false;
}
So the problem happens as follows. When I use Start() to call this method and pass it a list, it works fine:
However, if I call this function by clicking a button, it sticks all of the elements at one spot. For example, after clicking the junk items button:
I am not sure exactly what is going wrong here, since the list is the same and the method being called is the same. Is a VerticalLayoutGroup only set up during Start(), or is there something else I need to do?
Thanks for taking a look at this!
So after hours of playing around with my code and looking at forums, it looks like I've found the answer to this question. You have to call
LayoutRebuilder.ForceRebuildLayoutImmediate([your content panel here].transform asRectTransform);
after you modify what's in a list. This fixes this problem! http://forum.unity3d.com/threads/dynamically-added-ui-doesnt-get-affected-by-layout-groups-and-content-size-fitters.355279/
Your answer
Follow this Question
Related Questions
uGUI Vertical Layout Group stretching objects 2 Answers
Horizontal Layout Group padding update via script 3 Answers
how to extend the GUILayout scrollview's function? 0 Answers
What is the LayoutElement.FlexibleWidth/FlexibleHeight above 1 for? 0 Answers
How do I code a custom LayoutGroup? 0 Answers