Unity 格子布局Item ScrollRect多列无限循环
关于unity ScrollRect单列无限循环,网上已经有不少了,应该很容易找到,这里就不多说,这里简单说下多列无限循环,至于多行,有需要的自己照着改下就好~ (最近优化用到,备忘下)
源码地址:https://download.csdn.net/download/bingo105/12922419
![效果展示](https://img-blog.csdnimg.cn/2020101412060147.gif#pic_center
首先搭下简单的ui
图片:
空间属性:
然后
我们需要复用的Item
好了,简单的准备工作完成,接着来看看相关代码吧。
新建一个脚本:MyLoopList
代码如下:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ICustomGridItem<T> where T : class
{
protected T info;
protected GameObject go;
public virtual void Init(GameObject go)
{
this.go = go;
}
public virtual void UpdateView()
{
}
public void SetInfo(T info)
{
this.info = info;
UpdateView();
}
}
public class MyLoopList<DataType, ItemType> where ItemType : ICustomGridItem<DataType>, new() where DataType : class
{
RectTransform scrollRect;
RectTransform contentTR;
public GameObject ItemGo;
public int GridHeight; //
public int GridWidth;
public int wholeItemCount; //格子总数
public int lineCount; //每一行的格子数
public float top;//边距
public float left;
public Vector2 space;
int line; //面板里的行数
float contentHeight; //content根据grid数量初始化后的高度
float lastContentRTy;
int itemCountInView; //面板里可容纳的最大Item数量
float scrollViewHeight; //面板的初始高度
int firstLineIndex; //当前面板中的第一个Item的index
LinkedList<RectTransform> itemList = new LinkedList<RectTransform>();
Dictionary<GameObject, ICustomGridItem<DataType>> gridList = new Dictionary<GameObject, ICustomGridItem<DataType>>();
DataType[] datas;
public void Init(DataType[] datas, float left,float top, Vector2 space, int gridHeight,
int gridWidth, int lineCount, int wholeItemCount, GameObject itemGo, RectTransform scrollRect)
{
this.scrollRect = scrollRect;
this.datas = datas;
GridHeight = gridHeight;
GridWidth = gridWidth;
this.lineCount = lineCount;
this.wholeItemCount = wholeItemCount;
this.space = space;
this.left = left;
this.top = top;
ItemGo = itemGo;
contentTR = scrollRect.Find("Viewport/Content").GetComponent<RectTransform>();
if (contentTR == null)
{
Debug.LogError("应该有叫'Content'的子物体");
return;
}
var rect = scrollRect.GetComponent<RectTransform>()</