unity ugui list 代码封装
时间: 2023-10-15 21:04:04 浏览: 104
unity_UGUI_合成代码.unitypackage
5星 · 资源好评率100%
以下是使用Unity UGUI创建可滚动列表的封装代码:
```csharp
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class ScrollableList : MonoBehaviour
{
public GameObject listItemPrefab;
public Transform contentPanel;
public ScrollRect scrollRect;
private List<GameObject> listItems = new List<GameObject>();
public void AddListItem(string text)
{
GameObject listItem = Instantiate(listItemPrefab) as GameObject;
listItem.transform.SetParent(contentPanel, false);
listItem.GetComponent<Text>().text = text;
listItems.Add(listItem);
UpdateContentSize();
}
public void RemoveListItem(int index)
{
if (index >= 0 && index < listItems.Count)
{
Destroy(listItems[index]);
listItems.RemoveAt(index);
UpdateContentSize();
}
}
public void ClearList()
{
foreach (GameObject listItem in listItems)
{
Destroy(listItem);
}
listItems.Clear();
UpdateContentSize();
}
private void UpdateContentSize()
{
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);
}
}
```
在这个封装代码中,我们将创建、添加、删除和清空列表项的功能封装成了公共函数。当添加、删除、或清空列表项时,我们都会调用`UpdateContentSize()`函数来重新计算内容面板的大小并设置为`contentPanel`的大小。这样,我们就可以在脚本中方便地使用这个可滚动列表了。
阅读全文