I am trying to transition from legacy GUI to the new UI. I need a Scroll Rect (using a ScrollBar) to display a set of Buttons, but the button functions and text strings are decided at runtime. Has anyone figured out if it is possible and how? I did not see it in the new UI tutorials. Thanks, guys.
Yes, it’s possible. Once you created the scroll structure all you need to be doing is adding the created objects as children of the object, which the ScrollRect points to as Content.
[SerializeField]
private GameObject buttonPrefab = null; // Assign button prefab in editor
[SerializeField]
private GameObject listContainer = null; // Assign Contents object in editor
private List<GameObject> items; // initialise this and fill with content that will display in the scroller
private void PopulateScroller()
{
foreach (GameObject item in items)
{
// Create button and put it in the scroll rect
GameObject button = Instantiate(buttonPrefab) as GameObject;
button.transform.SetParent(listContainer.transform, false);
// Customise the button with object from list
GameObject captured = item;
button.GetComponentInChildren<Text>().text = captured.name;
button.GetComponent<Button>().onClick.AddListener(() => OnSelected(captured.name));
}
}
private void OnSelected(string name)
{
// What to do when button was clicked
Debug.Log(name);
}