- Home /
[4.6 UI] Is it possible to alter the content of a Scroll Rect at runtime?
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.
Find any help in this thread? http://forum.unity3d.com/threads/scrollrect-runtime-content.263815/
Answer by AyAMrau · Dec 04, 2014 at 02:48 PM
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);
}
Is the WorldPositionStays bool responsible for the button position in the ScrollView? Whether it is true or false, all buttons seem to appear on top of the previous one.
it's responsible for making the button take the position of the parent (previously you had to set the local position to 0 after parenting).
Does your content object have a Vertical or Horizontal Layout Group? Cause that's a way to keep them all next to each other.
Will use a layout group. Thank you again, you helped a lot. Cheers. :)
Plus 1 to the "AddListener(() => OnSelected(captured.name))" part... learned a lot from this! Thanks!
Your answer
Follow this Question
Related Questions
Scroll Rect Problem 1 Answer
unity 4.6 new UI Android soft buttons 1 Answer
Event Trigger and Scripting, how to avoid duplicate initialization? 1 Answer
UI world space text resolution 1 Answer
Unity 4.6 New UI Touch Detection 1 Answer