脚本挂上即可
public class ScrollPage : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
private ScrollRect rect;
//页面:0,1,2,3 索引从0开始
private List
private int currentPageIndex = -1;
//滑动速度
public float smooting = 4;
//单页显示个数
public int perPageCount;
//滑动的起始坐标
private float targethorizontal = 0;
//是否拖拽结束
bool isDrag = false;
///
/// 用于返回一个页码,-1说明page的数据为0
///
public System.Action
float startime = 0f;
float delay = 0.1f;
void Start()
{
rect = transform.GetComponent
startime = Time.time;
}
void Update()
{
if (Time.time < startime + delay)
{
return;
}
UpdatePages();
if (!isDrag && pages.Count > 0)
{
rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, Time.deltaTime * smooting);
}
}
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
}
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
float posX = rect.horizontalNormalizedPosition;
int index = 0;
//假设离第一位最近
float offset = Mathf.Abs(pages[index] - posX);
for (int i = 1; i < pages.Count; i++)
{
float temp = Mathf.Abs(pages[i] - posX);
if (temp < offset)
{
index = i;
offset = temp;
}
}
if (index != currentPageIndex)
{
currentPageIndex = index;
if(OnPageChanged != null)
{
OnPageChanged(pages.Count, currentPageIndex);
}
}
targethorizontal = pages[index];
}
private void UpdatePages()
{
// 获取子对象的数量
int count = this.rect.content.childCount;
int temp = 0;
for (int i = 0; i < count; i++)
{
if (this.rect.content.GetChild(i).gameObject.activeSelf)
{
temp++;
}
}
count = temp;
if (pages.Count != count)
{
if (count != 0)
{
pages.Clear();
for (int i = 0; i < count; i++)
{
float page = 0;
if (count != 1)
{
page = i / ((float)(count - 1));
}
pages.Add(page);
}
}
OnEndDrag(null);
}
}
public void SetTargethorizontal()
{
targethorizontal = 0;
}
}