这篇文章主要为大家详细介绍了UGUI ScrollRect实现带按钮翻页支持拖拽,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了UGUI ScrollRect带按钮翻页支持拖拽的具体代码,供大家参考,具体内容如下
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
/// <summary>
/// 略知CSharp
/// </summary>
public class ScrollRectHelper : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
public float smooting = 5; //滑动速度
public List<GameObject> listItem; //scrollview item
public int pageCount = 3; //每页显示的项目
ScrollRect srect;
float pageIndex; //总页数
bool isDrag = false; //是否拖拽结束
List<float> listPageValue = new List<float> { 0 }; //总页数索引比列 0-1
float targetPos = 0; //滑动的目标位置
float nowindex = 0; //当前位置索引
void Awake()
{
srect = GetComponent<ScrollRect>();
ListPageValueInit();
}
//每页比例
void ListPageValueInit()
{
pageIndex = (listItem.Count / pageCount)-1;
if (listItem != null && listItem.Count != 0)
{
for (float i = 1; i <= pageIndex; i++)
{
listPageValue.Add((i / pageIndex));
}
}
}
void Update()
{
if (!isDrag)
srect.horizontalNormalizedPosition = Mathf.Lerp(srect.horizontalNormalizedPosition, targetPos, Time.deltaTime * smooting);
}
/// <summary>
/// 拖动开始
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
}
/// <summary>
/// 拖拽结束
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
var tempPos = srect.horizontalNormalizedPosition; //获取拖动的值
var index = 0;
float offset = Mathf.Abs(listPageValue[index] - tempPos); //拖动的绝对值
for (int i = 1; i < listPageValue.Count; i++)
{
float temp = Mathf.Abs(tempPos - listPageValue[i]);
if (temp < offset)
{
index = i;
offset = temp;
}
}
targetPos = listPageValue[index];
nowindex = index;
}
public void BtnLeftGo()
{
nowindex = Mathf.Clamp(nowindex - 1, 0, pageIndex);
targetPos = listPageValue[Convert.ToInt32(nowindex)];
}
public void BtnRightGo()
{
nowindex = Mathf.Clamp(nowindex + 1, 0, pageIndex);
targetPos = listPageValue[Convert.ToInt32(nowindex)];
}
}
DEMO 下载地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:UGUI ScrollRect实现带按钮翻页支持拖拽
基础教程推荐
猜你喜欢
- ZooKeeper的安装及部署教程 2023-01-22
- C# 调用WebService的方法 2023-03-09
- C# windows语音识别与朗读实例 2023-04-27
- unity实现动态排行榜 2023-04-27
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- C#控制台实现飞行棋小游戏 2023-04-22
- 一个读写csv文件的C#类 2022-11-06
- C#类和结构详解 2023-05-30
- C# List实现行转列的通用方案 2022-11-02
- winform把Office转成PDF文件 2023-06-14