unity分页滚动

unity分页滚动

如果要做到分页滚动,首先要做到滚动

滚动步骤:

  1. 添加一个新的Image,并加上Scroll Rect组件
  2. 将想要滚动的物体放在新添加的Image下
  3. Scroll Rect组件中的Content拉取为想要滚动的物体
  4. 默认是水平和垂直都会滑动,可以勾选HorizontalVertical进行相应方向的滑动选择
  5. 这时已经可以滑动了,但是超出边界的并没有截取出来,直接给Image添加Mask组件即可,把组件中的Show Mash Graphic取消,还可以将Image的白色空白给取消

如下图所示
unity分页滚动_第1张图片

分页滑动滚动

给image添加如下脚本即可,很简单,看看注释。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
//继承这两个接口并实现 IBeginDragHandler,IEndDragHandler
public class ScrollPanel : MonoBehaviour , IBeginDragHandler , IEndDragHandler
{
	//获取ScrollRect组件
    private ScrollRect _scrollRect;
	//分页数组,滑动的水平值在0~1之间,我们要分4页
    private float[] _posArray = new float[4]{ 0, 0.333f, 0.666f, 1 };

    // Start is called before the first frame update
    void Start()
    {
        _scrollRect = GetComponent<ScrollRect>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
    }
	//实现的接口,当滑动结束时
    public void OnEndDrag(PointerEventData eventData)
    {
    	//获得滑动的水平值
        float posX = _scrollRect.horizontalNormalizedPosition;
        int resultIndex = 0;
        float minDiffValue = 1;

		//循环找出滑动的水平值 最接 近我们定义的数组的index
        for (int i = 0; i < _posArray.Length; i++)
        {
            if (Mathf.Abs(_posArray[i] - posX) < minDiffValue)
            {
                minDiffValue = Mathf.Abs(_posArray[i] - posX);
                resultIndex = i;
            }
        }
		//赋值即可
        _scrollRect.horizontalNormalizedPosition = _posArray[resultIndex];
    }
}

你可能感兴趣的:(unity)