unity ugui list 代码
时间: 2023-10-15 14:02:13 浏览: 209
以下是使用Unity UGUI创建可滚动列表的示例代码:
```csharp
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class MyList : MonoBehaviour
{
public GameObject listItemPrefab;
public Transform contentPanel;
public ScrollRect scrollRect;
private List<GameObject> listItems = new List<GameObject>();
void Start()
{
// 创建列表项
for (int i = 0; i < 20; i++)
{
GameObject listItem = Instantiate(listItemPrefab) as GameObject;
listItem.transform.SetParent(contentPanel, false);
listItem.GetComponent<Text>().text = "Item " + i;
listItems.Add(listItem);
}
// 计算内容面板大小并设置ScrollRect
GridLayoutGroup gridLayout = contentPanel.GetComponent<GridLayoutGroup>();
float cellSize = gridLayout.cellSize.y + gridLayout.spacing.y;
float spacing = gridLayout.padding.top + gridLayout.padding.bottom + gridLayout.spacing.y;
int rowCount = Mathf.CeilToInt(listItems.Count / (float)gridLayout.constraintCount);
float height = rowCount * cellSize + spacing;
contentPanel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, height);
}
}
```
这里使用了一个名为`listItemPrefab`的预制体作为列表项,`contentPanel`指向Scroll View的内容面板,`scrollRect`则指向Scroll View本身。在`Start()`函数中,首先创建20个列表项并加入到`listItems`列表中,然后根据GridLayoutGroup的设置计算内容面板的大小,并将其设置为`contentPanel`的大小,最后将`contentPanel`的高度设置为计算出的高度。这样,在运行时,就可以在Scroll View中看到可滚动的列表了。
阅读全文