效果展示
有鼠标拖动来直接实现滑动
实现步骤
第一步创建Scroll View UI
在场景里面创建Scroll View UI
第二步挂载Grid Layout Group组件
找到下面的Content物体
给其挂载Grid Layout Group组件,并且按照自己需求设置里面的内容
第三步添加脚本
给Scroll View组件添加我们自己写的脚本SlideScrollView
脚本如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using DG.Tweening;
public class SlideScrollView : MonoBehaviour,IBeginDragHandler,IEndDragHandler
{
private RectTransform contentTrans;
private float beginMousePositionX;
private float endMousePositionX;
private ScrollRect scrollRect;
public int cellLength;
public int spaceing;
public int leftOffset;
private float moveOneItemLength;
private Vector3 currentContentLocalPos;//上一次的位置
public int totalItemNum;
private int currenIndex;
private void Awake()
{
scrollRect = GetComponent<ScrollRect>();
contentTrans = scrollRect.content;
moveOneItemLength = cellLength + spaceing;
currentContentLocalPos = contentTrans.localPosition;
currenIndex = 1;
}
public void OnEndDrag(PointerEventData eventData)
{
endMousePositionX = Input.mousePosition.x;
float offSetX = 0;
float moveDistance = 0;//当次需要滑动的距离
offSetX = beginMousePositionX - endMousePositionX;
if (offSetX > 0)//右滑
{
if(currenIndex>=totalItemNum)
{
return;
}
moveDistance = -moveOneItemLength;
currenIndex++;
}
else//左滑
{
if (currenIndex <= 1)
{
return;
}
moveDistance = moveOneItemLength;
currenIndex--;
}
DOTween.To(() => contentTrans.localPosition, lerpValue => contentTrans.localPosition = lerpValue, currentContentLocalPos + new Vector3(moveDistance, 0, 0), 0.5f).SetEase(Ease.InOutQuint);
currentContentLocalPos += new Vector3(moveDistance, 0, 0);
}
public void OnBeginDrag(PointerEventData eventData)
{
beginMousePositionX = Input.mousePosition.x;
}
}
第四步赋值
在Unity给脚本里赋值
说明:
Cell Length:为Grid Layout Group组件的Cell Size的x的值
Spaceing:为Grid Layout Group组件的Spacing的x的值
LeftOffset:为Grid Layout Group组件的Padding的Left的值
TotalItemNum:为总共要滑动的物体的个数
重要说明
代码中使用了DoTween插件
需要去官网下载插件:DoTween
下载后将其解压直接拖入项目中就可以使用了
可以将Scroll View中的惯性√去掉来获得更好的效果