[c#]代码库
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
//需要继承IBeginDragHandler,IEndDragHandler这两个接口
public class LevelButtonScrollRect : MonoBehaviour ,IBeginDragHandler,IEndDragHandler
{
//ScrollRect滑动组件
private ScrollRect scrollRect;
//鼠标释放时组件滑动的速度
public float smoothing = 4;
//4个页面的位置节点
private float[] pageArray=new float[]{ 0,0.333f,0.666f,1 };
//toggle组件,用来页面和页面按钮的同步,需在对象物体赋值
public Toggle[] toggleArray;
//用来存储 推算出来 需停靠页面 的值
private float targetHorizontalPosition=0;
//判断是否处于拖拽状态
private bool isDraging = false;
void Start ()
{
scrollRect = GetComponent<ScrollRect>();
}
void Update ()
{
if(isDraging) //Mathf.Lerp让物体平衡滑动
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,
targetHorizontalPosition, Time.deltaTime*smoothing);
}
public void OnBeginDrag(PointerEventData eventData) //处于拖拽状态
{
isDraging = false;
}
public void OnEndDrag(PointerEventData eventData) //拖拽结束
{
isDraging = true;
float posX = scrollRect.horizontalNormalizedPosition;
int index = 0;
float offset = Mathf.Abs(pageArray[index] - posX);
for (int i = 1; i < pageArray.Length; i++)
{
float offsetTemp = Mathf.Abs(pageArray[i] - posX);
if (offsetTemp < offset)
{
index = i;
offset = offsetTemp;
}
}
targetHorizontalPosition = pageArray[index];
toggleArray[index].isOn = true;
//scrollRect.horizontalNormalizedPosition = pageArray[index];
}
//4个页面,4个调用方法
public void MoveToPage1(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[0];
}
}
public void MoveToPage2(bool isOn) {
if (isOn) {
targetHorizontalPosition = pageArray[1];
}
}
public void MoveToPage3(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[2];
}
}
public void MoveToPage4(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[3];
}
}
}
[代码运行效果截图]