一,新建ScrollView ,目录结构如图:
二,在content下编辑需要显示的关卡内容,这里设置为一页显示一个button集合,14个button为一整页,一次只显示一页内容:
下面上代码:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
public class ScrollRectHelper : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
private float smooting; //滑动速度
private float normalSpeed = 5;
private float highSpeed = 100;
private int pageCount = 1; //每页显示的项目
public GameObject listItem;
private ScrollRect sRect;
private float pageIndex; //总页数
private bool isDrag = false; //是否拖拽结束
private List<float> listPageValue = new List<float> { 0 }; //总页数索引比列 0-1
private float m_targetPos = 0; //滑动的目标位置
//public float TargetPos
//{
// set { m_targetPos = value; }
//}
private float nowindex = 0; //当前位置索引
private float beginDragPos;
private float endDragPos;
private float sensitivity = 0.05f; //灵敏度
void Awake()
{
sRect = this.GetComponent<ScrollRect>();
ListPageValueInit();
smooting = normalSpeed;
//StartCoroutine(ToTarPage(1));
}
//每页比例
void ListPageValueInit()
{
pageIndex = (listItem.transform.childCount / pageCount) - 1;
if (listItem != null && listItem.transform.childCount != 0)
{
for (float i = 1; i <= pageIndex; i++)
{
listPageValue.Add((i / pageIndex));
}
}
}
public IEnumerator ToTarPage(int tarIndex)
{
m_targetPos = tarIndex;
smooting = highSpeed;
yield return null;
smooting = normalSpeed;
}
void Update()
{
if (!isDrag)
sRect.horizontalNormalizedPosition = Mathf.Lerp(sRect.horizontalNormalizedPosition, m_targetPos, Time.deltaTime * smooting);
}
/// <summary>
/// 拖动开始
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
beginDragPos = sRect.horizontalNormalizedPosition;
}
/// <summary>
/// 拖拽结束
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
endDragPos = sRect.horizontalNormalizedPosition; //获取拖动的值
endDragPos = endDragPos > beginDragPos ? endDragPos + sensitivity : endDragPos - sensitivity;
int index = 0;
float offset = Mathf.Abs(listPageValue[index] - endDragPos); //拖动的绝对值
for (int i = 1; i < listPageValue.Count; i++)
{
float temp = Mathf.Abs(endDragPos - listPageValue[i]);
if (temp < offset)
{
index = i;
offset = temp;
}
}
m_targetPos = listPageValue[index];
nowindex = index;
}
public void BtnLeftGo()
{
nowindex = Mathf.Clamp(nowindex - 1, 0, pageIndex);
m_targetPos = listPageValue[Convert.ToInt32(nowindex)];
}
public void BtnRightGo()
{
nowindex = Mathf.Clamp(nowindex + 1, 0, pageIndex);
m_targetPos = listPageValue[Convert.ToInt32(nowindex)];
}
}