新建一个Scroll View,将一下脚本挂在到Scroll View即可
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
//自动设置竖直滚动列表
public class UIListView : MonoBehaviour
{
// Start is called before the first frame update
public RectTransform itemMode; //item模板
public string viewportName;
public string contentName;
private GameObject content;
public int listCount;
private List<GameObject> gameObjects;
private void Awake()
{
ScrollRect sr = this.gameObject.GetComponent<ScrollRect>();
//设置为只能竖直滚动
sr.horizontal = false;
sr.vertical = true;
gameObjects = new List<GameObject>();
viewportName = viewportName == "" ? "Viewport" : viewportName;
contentName = contentName == "" ? "Content" : contentName;
content = this.transform.Find(viewportName+"/"+contentName).gameObject;
try
{
//添加自适应高度布局
ContentSizeFitter csf = content.AddComponent<ContentSizeFitter>();
csf.verticalFit = ContentSizeFitter.FitMode.MinSize;
//添加子物体排版列表布局
VerticalLayoutGroup vlg = content.AddComponent<VerticalLayoutGroup>();
vlg.childControlHeight = false;
gameObjects.Clear();
for (int i = 0;i<listCount;i++)
{
GameObject g = Instantiate(itemMode.gameObject,content.transform);
gameObjects.Add(g);
}
}
catch(Exception e)
{
print(e.Message);
}
}
void Start()
{
foreach(GameObject g in gameObjects)
{
//在这里初始化item
}
}
// Update is called once per frame
void Update()
{
}
}