UGUI ScrollRect實(shí)現(xiàn)帶按鈕翻頁(yè)支持拖拽
更新時(shí)間:2020年05月22日 09:06:50 作者:代碼妖
這篇文章主要為大家詳細(xì)介紹了UGUI ScrollRect實(shí)現(xiàn)帶按鈕翻頁(yè)支持拖拽,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了UGUI ScrollRect帶按鈕翻頁(yè)支持拖拽的具體代碼,供大家參考,具體內(nèi)容如下

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; //滑動(dòng)速度
public List<GameObject> listItem; //scrollview item
public int pageCount = 3; //每頁(yè)顯示的項(xiàng)目
ScrollRect srect;
float pageIndex; //總頁(yè)數(shù)
bool isDrag = false; //是否拖拽結(jié)束
List<float> listPageValue = new List<float> { 0 }; //總頁(yè)數(shù)索引比列 0-1
float targetPos = 0; //滑動(dòng)的目標(biāo)位置
float nowindex = 0; //當(dāng)前位置索引
void Awake()
{
srect = GetComponent<ScrollRect>();
ListPageValueInit();
}
//每頁(yè)比例
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>
/// 拖動(dòng)開(kāi)始
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
}
/// <summary>
/// 拖拽結(jié)束
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
var tempPos = srect.horizontalNormalizedPosition; //獲取拖動(dòng)的值
var index = 0;
float offset = Mathf.Abs(listPageValue[index] - tempPos); //拖動(dòng)的絕對(duì)值
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 下載地址
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c# winform窗口一直置頂顯示在桌面最上方或最底層的方法
winform窗口一直置頂顯示在桌面最上方,這樣的功能真的很實(shí)用的,很多的軟件窗口都有這樣的功能,本文也來(lái)實(shí)現(xiàn)一個(gè),感興趣的你千萬(wàn)不要錯(cuò)過(guò)了,希望本文對(duì)你有所幫助2013-01-01
C#使用throw和throw?ex拋出異常的區(qū)別介紹
這篇文章介紹了C#使用throw和throw?ex拋出異常的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10
C#簡(jiǎn)單獲取全屏中鼠標(biāo)焦點(diǎn)位置坐標(biāo)的方法示例
這篇文章主要介紹了C#簡(jiǎn)單獲取全屏中鼠標(biāo)焦點(diǎn)位置坐標(biāo)的方法,涉及C#針對(duì)鼠標(biāo)位置Position屬性的簡(jiǎn)單操作技巧,需要的朋友可以參考下2017-07-07

