Unity工具整理----滑页工具

在网上的基础上修改了代码,可根据content子物体来自动设置content的容器大小,并自动将子物体排序由上至下

场景资源如下,在canvas下面

  1. Scroll View 滑动的内容,鼠标拖拽滑动显示
  2. TextNumber 显示当前页的索引
  3. InputFiled 填入需要跳转的页数
  4. Button 点击后跳转到指定页
    在这里插入图片描述

将GameController.cs 挂载在Canvans上
挂载对应的组件

PageView.cs 挂载在ScrollView上
在这里插入图片描述

改工具能上下滑动 也能左右滑动 只需要设置Scroll View上Scroll Recrt组件上的变量即可
Horizontal 纵向
Vertical 横向
在这里插入图片描述
下面贴代码
GameController.cs

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;

public class GameController : MonoBehaviour {
    [SerializeField]
    private Text pageNumber;
    [SerializeField]
    private InputField inputField;
    [SerializeField]
    //private PageView pageView;
    private PageView pageView;
	// Use this for initialization
	void Start () {
        pageNumber.text = string.Format ("当前页码:0");
        pageView.OnPageChanged = pageChanged;
    }

    void pageChanged (int index) {
        pageNumber.text = string.Format ("当前页码:{0}" , index.ToString ());
    }

    public void onClick () {
        try {
            int index = int.Parse (inputField.text);
            pageView.pageTo (index);
        } catch(Exception ex) {
            Debug.LogWarning ("请输入数字"+ex.ToString()); 
        }
    }

    void Destroy () {
        pageView.OnPageChanged = null;
    }
}

PageView

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

public class PageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
    private ScrollRect rect;
    private float targetvertical;
    private bool isDrag = false;
    public List<float> posList = new List<float>();
    private int currentPageIndex = -1;
    public Action<int> OnPageChanged;

    private bool stopMove = true;
    public float smooting = 4;
    public float sensitivity = 0;
    private float startTime;

    private float startPos;
    float width;
    float heigth;

    private void Awake()
    {
        rect = transform.GetComponent<ScrollRect>();
        width = GetComponent<RectTransform>().rect.width;
        heigth = GetComponent<RectTransform>().rect.height;

        if (rect.vertical)
            Scroll2Vertical();
        else if (rect.horizontal)
            Scroll2Horizontal();
    }

    private void Scroll2Horizontal()
    {

        /*  横向滑动 */
        rect.content.GetComponent<RectTransform>().sizeDelta = new Vector2(width * rect.content.transform.childCount, heigth);
        /* 自左到右 */
        //rect.content.transform.localPosition = new Vector2(0, 0);
        /* 自右到左 */
        rect.content.transform.localPosition = new Vector2(-rect.content.GetComponent<RectTransform>().rect.width - width, 0);

        for (int i = 0; i < rect.content.transform.childCount; i++)
        {
            rect.content.GetChild(i).localPosition = new Vector2(width * (0.5f + i), -160);
        }
        float horizontalLength = rect.content.rect.width - width;

        /// 索引获取
        posList.Add(0);
        for (int i = 1; i < rect.content.transform.childCount - 1; i++)
        {
           
            posList.Add(width * i / horizontalLength);
        }
        posList.Add(1);
    }

    private void Scroll2Vertical()
    {
        /* 纵向滑动 */
        rect.content.GetComponent<RectTransform>().sizeDelta = new Vector2(width, heigth * rect.content.transform.childCount);
        /* 自下而上 */
        rect.content.transform.localPosition = new Vector2(0, rect.content.GetComponent<RectTransform>().rect.height - heigth);
        /* 自上而下 */
        //rect.content.transform.localPosition = new Vector2(0, 0);

        for (int i = 0; i < rect.content.transform.childCount; i++)
        {
            rect.content.GetChild(i).localPosition = new Vector2(240, -heigth * (0.5f + i));
        }

        float verticalLength = rect.content.rect.height - heigth;
        /// 索引获取
        posList.Add(0);
        for (int i = 1; i < rect.content.transform.childCount - 1; i++)
        {
            posList.Add(heigth * i / verticalLength);
        }
        posList.Add(1);
    }


    // Update is called once per frame
    void Update()
    {
        if (!isDrag && !stopMove)
        {
            startTime += Time.deltaTime;
            float t = startTime * smooting;
            rect.verticalNormalizedPosition = Mathf.Lerp(rect.verticalNormalizedPosition, targetvertical, t);
            rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targetvertical, t);
            if (t >= 1)
                stopMove = true;
        }
    }

    public void pageTo(int index)
    {
        if (index >= 0 && index < posList.Count)
        {
            rect.verticalNormalizedPosition = posList[index];
            rect.horizontalNormalizedPosition = posList[index];
            SetPageIndex(index);
        }
        else
        {
            Debug.LogWarning("页码不存在");
        }
    }

    public void SetPageIndex(int index)
    {
        if (currentPageIndex != index)
        {
            currentPageIndex = index;
            if (OnPageChanged != null)
                OnPageChanged(index);
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = true;
        if (rect.vertical)
            startPos = rect.verticalNormalizedPosition;
        else if (rect.horizontal)
            startPos = rect.horizontalNormalizedPosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        float pos = 0;
        if (rect.horizontal)
            pos = rect.horizontalNormalizedPosition;
        else if (rect.vertical)
            pos = rect.verticalNormalizedPosition;
        pos += ((pos - startPos) * sensitivity);
        pos = pos < 1 ? pos : 1;
        pos = pos > 0 ? pos : 0;
        int index = 0;
        float offset = Mathf.Abs(posList[index] - pos);
        for (int i = 1; i < posList.Count; i++)
        {
            float temp = Mathf.Abs(posList[i] - pos);
            if (temp < offset)
            {
                index = i;
                offset = temp;
            }
        }

        SetPageIndex(index);

        targetvertical = posList[index];
        isDrag = false;
        startTime = 0;
        stopMove = false;
    }
}

效果演示
在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值