层级结构
```
-
Canvas
-
Scroll View
-
Viewport
-
Content (Vertical Layout Group)
-
Item1 (Prefab)
-
Item2 (Prefab)
...
```
详细设置步骤
-
创建 Canvas
-
添加 Scroll View 组件
-
在 Scroll View 下创建 Content 子对象
-
添加 Vertical Layout Group 组件到 Content
-
创建列表项预制体
```
Unity 场景配置代码
```csharp
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class VerticalLayoutGroup : MonoBehaviour
{
public GameObject itemPrefab; // 拖入预制体
public Transform contentParent; // 拖入 Scroll View 的 Content
void Start()
{
// 清除可能存在的默认子对象
foreach (Transform child in contentParent)
{
Destroy(child.gameObject);
}
PopulateList(20);
}
void PopulateList(int count)
{
for (int i = 0; i < count; i++)
{
// 实例化预制体
GameObject item = Instantiate(itemPrefab, contentParent);
// 获取 TextMeshProUGUI 组件
TextMeshProUGUI textComponent = item.GetComponentInChildren<TextMeshProUGUI>();
if (textComponent != null)
{
textComponent.text = "列表项 " + (i + 1);
}
}
}
}
```
预制体制作
-
创建新的 UI 面板(Right Click -> UI -> Panel)
-
添加 TextMeshPro - Text 组件
-
调整大小和样式
-
将面板拖入项目的 Prefabs 文件夹
-
将预制体拖入脚本的 Item Prefab 字段
Scroll View 设置
-
确保 Scroll View 组件配置正确
-
Content 的 Vertical Layout Group 属性:
-
Child Force Expand: 勾选 Width 和 Height
-
Spacing: 可以设置间距(如 10)
- Content Size Fitter 组件:
- Vertical Fit: Preferred Size
性能优化建议
-
对于大量数据,考虑使用对象池
-
使用 `ScrollRect` 的虚拟化视图
-
动态加载和卸载列表项