NGUI版本3.0.9 f4
脚本的作用:使用10个甚至更少的item模拟成百上千的item数据。在滑动过程中,如果拖到最后面的时候,会拿第一个过来补位。所以要正确的设置补位的那个item的数据。滑到最前面也是一样,用最后面的那个过来补位。
方法:
1、脚本放在Scroll View下面的UIGrid的那个物体上
2、UIScrollView的Restrict Within Panel勾选掉
3、Scroll View上面的UIPanel的Cull勾选上
4、你的每一个Item都放上一个UIWidget,调整到合适的大小(用它的Visiable)
5、仅仅是提供思路,具体每个Item的内容怎么更新什么的自己研究吧。
6、应该没问题了。有问题加群问。
附代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(UIGrid))]
public class SZUILoopScrollView : MonoBehaviour {
public string perfix = string.Empty;
private List<UIWidget> itemList = new List<UIWidget>();
private Vector4 posParam;
private Transform cachedTransform;
void Awake()
{
cachedTransform = this.transform;
UIGrid grid = this.GetComponent<UIGrid>();
float cellWidth = grid.cellWidth;
float cellHeight = grid.cellHeight;
posParam = new Vector4(cellWidth, cellHeight,
grid.arrangement == UIGrid.Arrangement.Horizontal ? 1 : 0,
grid.arrangement == UIGrid.Arrangement.Vertical ? 1 : 0);
}
void Start()
{
for (int i=0; i<cachedTransform.childCount; ++i)
{
Transform t = cachedTransform.GetChild(i);
UIWidget uiw = t.GetComponent<UIWidget>();
uiw.name = string.Format("{0}_{1:D3}", perfix, itemList.Count);
itemList.Add(uiw);
}
}
void LateUpdate()
{
if (itemList.Count > 1)
{
int sourceIndex = -1;
int targetIndex = -1;
int sign = 0;
bool firstVislable = itemList[0].isVisible;
bool lastVisiable = itemList[itemList.Count-1].isVisible;
// if first and last both visiable or invisiable then return
if (firstVislable == lastVisiable)
{
return;
}
if (firstVislable)
{
// move last to first one
sourceIndex = itemList.Count-1;
targetIndex = 0;
sign = -1;
}
else if (lastVisiable)
{
// move first to last one
sourceIndex = 0;
targetIndex = itemList.Count-1;
sign = 1;
}
if (sourceIndex > -1)
{
UIWidget movedWidget = itemList[sourceIndex];
Vector3 offset = new Vector3(sign*posParam.x * posParam.z, sign*posParam.y * posParam.w, 0);
movedWidget.cachedTransform.localPosition = itemList[targetIndex].cachedTransform.localPosition + offset;
// change item index
itemList.RemoveAt(sourceIndex);
itemList.Insert(targetIndex, movedWidget);
}
}
}
}