Unity实现一次一页的滑动效果(可以直接使用)

bt365官网哪个真的 2025-07-09 17:12:49 admin 2480 332
Unity实现一次一页的滑动效果(可以直接使用)

目录

效果展示实现步骤第一步创建Scroll View UI第二步挂载Grid Layout Group组件第三步添加脚本第四步赋值

重要说明

效果展示

有鼠标拖动来直接实现滑动

实现步骤

第一步创建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();

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中的惯性√去掉来获得更好的效果

相关推荐

为什么我手机网络很差
义乌365人工客服电话多少

为什么我手机网络很差

06-27 222
世界杯丨2022卡塔尔世界杯32强巡礼
义乌365人工客服电话多少

世界杯丨2022卡塔尔世界杯32强巡礼

07-03 999
什么是SP值?SP值详解
和365差不多的平台有哪些

什么是SP值?SP值详解

07-03 675