Unity中实现ViewPage、ScrollSnap

之前分享过一片关于弹性滚动列表的文章: Unity中实现弹性滚动列表基于UGUI

这次分享一个基于ScrollView的滑屏列表。移动原生平台应该称为ViewPage吧。先看一下预览。

(作者链接:Unity Forums)

完整代码如下:


using System;
using UnityEngine.EventSystems;

    [RequireComponent (typeof (ScrollRect))]
    [AddComponentMenu ("UI/Extensions/Horizontal Scroll Snap")]
    public class HorizontalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler {
        private Transform _screensContainer;

        private int _screens = 1;
        private int _startingScreen = 1;

        private bool _fastSwipeTimer = false;
        private int _fastSwipeCounter = 0;
        private int _fastSwipeTarget = 30;

        private System.Collections.Generic.List _positions;
        private ScrollRect _scroll_rect;
        private Vector3 _lerp_target;
        private bool _lerp;

        private int _containerSize;

        [Tooltip ("The gameobject that contains toggles which suggest pagination. (optional)")]
        public GameObject Pagination;

        [Tooltip ("Button to go to the next page. (optional)")]
        public GameObject NextButton;
        [Tooltip ("Button to go to the previous page. (optional)")]
        public GameObject PrevButton;

        public Boolean UseFastSwipe = true;
        public int FastSwipeThreshold = 100;

        private bool _startDrag = true;
        private Vector3 _startPosition = new Vector3 ();
        private int _currentScreen;
        public float _speed=10;

        // Use this for initialization
        void Start () {
            _scroll_rect = gameObject.GetComponent ();
            _screensContainer = _scroll_rect.content;
            DistributePages ();
            ChangeBulletsInfo(0);

            _screens = _screensContainer.childCount;
            Debug.Log(_scroll_rect.horizontalNormalizedPosition);

            _lerp = false;

            _positions = new System.Collections.Generic.List ();

            if (_screens > 0) {
                for (int i = 0; i < _screens; ++i) {
                    _scroll_rect.horizontalNormalizedPosition = (float) i / (float) (_screens - 1);
                    Debug.Log(_scroll_rect.horizontalNormalizedPosition);

                    _positions.Add (_screensContainer.localPosition);
                }
            }


            _scroll_rect.horizontalNormalizedPosition = (float) (_startingScreen - 1) / (float) (_screens - 1);

            _containerSize = (int) _screensContainer.gameObject.GetComponent ().offsetMax.x;

            Debug.Log(_scroll_rect.horizontalNormalizedPosition);

            if (NextButton)
                NextButton.GetComponent

Demo地址:扫码=>历史消息=>当前文章末尾获取

Unity中实现ViewPage、ScrollSnap_第1张图片

阅读原文

你可能感兴趣的:(Unity3D)