Unity3D实现页面的滑动切换功能

效果展示

Unity3D实现页面的滑动切换 效果

文章目录


前言

``

好记性不如烂笔头!

一、先上代码

复制代码
/**********************************************************************
 文件信息
 文件名(File Name):                PageView.cs
 作者(Author):                      TianWenQuan
 创建时间(CreateTime):             #CREATETIME#
 **********************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
namespace Twq
{
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.EventSystems;
    using System;
    using UnityEngine.Events;
    using System.Reflection;
    //using RenderHeads.Media.AVProVideo.Demos;
    //using RenderHeads.Media.AVProVideo;

    /// <summary>
    /// 滑动页面效果
    /// </summary>
    public class PageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
    {
        public static PageView pageViewIn;
        private ScrollRect rect;
        private float targethorizontal = 0;
        private List<float> posList = new List<float>();//存四张图片的位置(0, 0.333, 0.666, 1) 
        private bool isDrag = true;
        private float startTime = 0;
        private float startDragHorizontal;
        private int curIndex = 0;

        public float speed = 2;      //滑动速度  
        public float sensitivity = 0;
        public Text curPage;

        public Transform Content;
       // public GameObject MediaPlayerUI_;
        //public MediaPlayer MediaPlayer_;

        public Transform PageList;//页面List
        public Button LeftButton;
        public Button RightButton;
        void Awake()
        {
            pageViewIn = this;
          
            LeftButton.onClick.AddListener(OnLeftButton);
            RightButton.onClick.AddListener(OnRightButton);
            for (int i = 0; i < PageList.childCount; i++)
            {
                int x = i;
                PageList.GetChild(x).transform.GetComponent<Toggle>().onValueChanged.AddListener((b) => {
                    if (b)
                    {
                        pageTo(x);
                    }
                });
            }


            rect = GetComponent<ScrollRect>();
            Debug.Log("rect.content.rect.width="+ rect.content.rect.width);
            Debug.Log(" GetComponent<RectTransform>().rect.width=" + GetComponent<RectTransform>().rect.width);
            float horizontalLength = rect.content.rect.width - GetComponent<RectTransform>().rect.width;
            Debug.Log(horizontalLength);
            var _rectWidth = GetComponent<RectTransform>().rect.width;
            Debug.Log(_rectWidth);
            Debug.Log(rect.content.transform.childCount);
            for (int i = 0; i < rect.content.transform.childCount; i++)
            {
                Debug.Log("---"+ (_rectWidth * i / horizontalLength).ToString());
                posList.Add(_rectWidth * i / horizontalLength);   //存四张图片的位置
            }
            curIndex = 0;
            curPage.text = String.Format("当前页码:0");
            Content.parent.parent.GetComponent<ScrollRect>().normalizedPosition = new Vector2(0, 1);
            LayoutRebuilder.ForceRebuildLayoutImmediate(Content.GetComponent<RectTransform>());
        }
       

        void Update()
        {
            if (!isDrag)
            {
                startTime += Time.deltaTime;
                float t = startTime * speed;
                //加速滑动效果
                rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, t);
                //缓慢匀速滑动效果
                // rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, Time.deltaTime * speed);

            }
        }
        /// <summary>
        /// 开始拖拽
        /// </summary>
        /// <param name="eventData"></param>
        public void OnBeginDrag(PointerEventData eventData)
        {
            Debug.Log("----开始拖动");
            isDrag = true;
            //开始拖动
            startDragHorizontal = rect.horizontalNormalizedPosition;  //horizontalNormalizedPosition这个参数是scrollRect滑动期间变化的x坐标值,在(0, 1)之间
        }

        /// <summary>
        /// 拖拽结束
        /// </summary>
        /// <param name="eventData"></param>
        public void OnEndDrag(PointerEventData eventData)
        {
            Debug.Log("拖动结束");
            float posX = rect.horizontalNormalizedPosition;
            int index = 0;
            float offset = Mathf.Abs(posList[index] - posX);  //计算当前位置与第一页的偏移量,初始化offect
            for (int i = 1; i < posList.Count; i++)
            {    //遍历页签,选取当前x位置和每页偏移量最小的那个页面
                float temp = Mathf.Abs(posList[i] - posX);
                if (temp < offset)
                {
                    index = i;
                    offset = temp;
                }
            }
            curIndex = index;
            targethorizontal = posList[curIndex]; //设置当前坐标,更新函数进行插值  
            isDrag = false;
            startTime = 0;
            curPage.text = String.Format("当前页码:{0}", curIndex.ToString());
            PageList.GetChild(curIndex + 1).transform.GetComponent<Toggle>().isOn = true;
        }
        
        /// <summary>
        /// 左边下一页 按钮
        /// </summary>
        public void OnLeftButton()
        {
            // Debug.Log("curIndex" + curIndex + "   posList.Count=" + PageList.childCount);
            if (curIndex <= 0)
            {
                 Debug.Log("左边不能点击了");
                return;
            }
            curIndex -= 1;
            PageList.GetChild(curIndex).transform.GetComponent<Toggle>().isOn = true;
            pageTo(curIndex);


        }
        /// <summary>
        /// 右边下一页 按钮
        /// </summary>
        public void OnRightButton()
        {
            // Debug.Log("curIndex" + curIndex + "  PageList=" + PageList.childCount);
            if (curIndex >= PageList.childCount - 1)
            {
                 Debug.Log("右边不能点击了");
                return;
            }
            curIndex += 1;
            PageList.GetChild(curIndex).transform.GetComponent<Toggle>().isOn = true;
            pageTo(curIndex);
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="index"></param>
        public void pageTo(int index)
        {
            if (index < 0) { return; }
            // Debug.Log("pageTo......index="+ index);
            curIndex = index;
            targethorizontal = posList[curIndex]; //设置当前坐标,更新函数进行插值  
            isDrag = false;
            startTime = 0;
            curPage.text = String.Format("当前页码:{0}", curIndex.ToString());
          //  MediaPlayer_.Stop();
            //MediaPlayerUI_.SetActive(false);
            if (index==1)
            {
             //   MediaPlayerUI_.SetActive(true);
            }
        }
    }
}

二、创建UI

1.创建Scroll View如下图,并挂载该脚本:

2.Content下创建几个Itme

对齐方式,可以根据需求使用以下:
!

因为代码里需要使用到Content的宽,让其自动填充宽度。最后删除该组件Content Size Fitte(不删除,可以自己尝试下,会影响我们要的翻动效果)

Content的对齐位置如下:

创建左右按钮和12345翻页按钮,就不仔细写了,都是调用脚本里的方法而已。

示例Dome:https://download.csdn.net/download/qq_37524903/88499409?spm=1001.2014.3001.5501

总结

好记性不如烂笔头

相关推荐
EQ-雪梨蛋花汤16 小时前
【Unity笔记】Unity 编辑器扩展:打造一个可切换 Config.assets 的顶部菜单插件
unity·编辑器·游戏引擎
SmalBox16 小时前
【URP】UnityHLSL顶点片元语义详解
unity·渲染
在路上看风景1 天前
9. Mono项目与Unity的关系
unity
在路上看风景1 天前
1.12 Memory Profiler Package - Summary
unity
SmalBox1 天前
【URP】Unity Shader Tags
unity·渲染
极客柒2 天前
Unity 塔防自用可视化路点寻路编辑器
unity·编辑器·游戏引擎
程序猿多布2 天前
Unity AssetBundle详解
unity·assetbundle
萘柰奈2 天前
Unity学习----【进阶】Addressables(二)--加载资源与打包及更新
学习·unity
lvcoc2 天前
unity 接入火山引擎API,包括即梦AI
windows·unity·ai·火山引擎
王家视频教程图书馆2 天前
2025年最新 unityHub游戏引擎开发2d手机游戏和桌面游戏教程
游戏·unity·游戏引擎