This should be very straightforward. Here is a simple example of how to accomplish this.
Here is the scene hierarchy, with the Content game object as a child of the Viewport, which in turn is a child of the Scrollbar gameobject. This is default Unity set up for a ScrollView game object.
The only other thing I've added is a Controller game object, to hold our sample scroll view populator script.
The Content game object needs two components: Vertical Layout Group and Content Size Fitter. I've added a bit of spacing in the Vertical Layout Group to separate the items. Child Force Expand Height should be unchecked.
Create the item template(s) as children of the Content game object. For the demo, the item template is very simple, just a background image with a text label child:
Here's the scene so far, with the item prefab in place:
When the template is to your satisfaction, save it as prefab and remove it from the scene hierarchy.
Here is an example script that will populate the ScrollView without the items overlapping:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PopulateScrollView : MonoBehaviour
{
[SerializeField] private Transform m_ContentContainer;
[SerializeField] private GameObject m_ItemPrefab;
[SerializeField] private int m_ItemsToGenerate;
void Start()
{
for(int i = 0; i < m_ItemsToGenerate; i++)
{
var item_go = Instantiate(m_ItemPrefab);
// do something with the instantiated item -- for instance
item_go.GetComponentInChildren<Text>().text = "Item #" + i;
item_go.GetComponent<Image>().color = i % 2 == 0 ? Color.yellow : Color.cyan;
//parent the item to the content container
item_go.transform.SetParent(m_ContentContainer);
//reset the item's scale -- this can get munged with UI prefabs
item_go.transform.localScale = Vector2.one;
}
}
}
One thing to note about the script -- I always reset the instantiated prefab's local scale after parenting it to a UI object, as sometimes (often, even) the scale gets messed up when taken out of its Canvas context.
Here are the exposed settings for this component, which was added to the Controller game object:
And here is the result when played:
SetParent(statsParent.transform, false)
? \$\endgroup\$LayoutRebuilder.ForceRebuildLayoutImmediate
after adding the object? \$\endgroup\$