層級結構
```
- Canvas
? - Scroll View
? ? - Viewport
? ? ? - Content (Vertical Layout Group)
? ? ? ? - Item1 (Prefab)
? ? ? ? - Item2 (Prefab)
? ? ? ? ...
```
詳細設置步驟
1. 創建 Canvas
2. 添加 Scroll View 組件
3. 在 Scroll View 下創建 Content 子對象
4. 添加 Vertical Layout Group 組件到 Content
5. 創建列表項預制體
```
?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);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
```
預制體制作
1. 創建新的 UI 面板(Right Click -> UI -> Panel)
2. 添加 TextMeshPro - Text 組件
3. 調整大小和樣式
4. 將面板拖入項目的 Prefabs 文件夾
5. 將預制體拖入腳本的 Item Prefab 字段
Scroll View 設置
1. 確保 Scroll View 組件配置正確
2. Content 的 Vertical Layout Group 屬性:
? ?- Child Force Expand: 勾選 Width 和 Height
? ?- Spacing: 可以設置間距(如 10)
3. Content Size Fitter 組件:
? ?- Vertical Fit: Preferred Size
性能優化建議
1. 對于大量數據,考慮使用對象池
2. 使用 `ScrollRect` 的虛擬化視圖
3. 動態加載和卸載列表項