Unity3D ScrollView跳转功能

最近在项目中需要用到ScrollView通过外部传进来的参数进行UI跳转的功能,一开始做了一个通过改变ScrollBar里的Value值跳转的,但是实际项目里是没有ScrollBar的,所以通过一个计算与DoTween插件实现了跳转功能。

第一步

新建一个ScrollView,删除掉ScrollView下的ScrollBar,然后再Content下添加自动排版组件,如图所示。


第二步

新建一个脚本,脚本内容如下

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using DG.Tweening;

public class ScrollViewDemoTest : MonoBehaviour
{
    public RectTransform Content;//调用Content的RectTransform组件
    public RectTransform ViewProt;//调用ViewPort的RectTransform组件
    // Use this for initialization
    void Start()
    {
        for (int i = 0; i < Content.childCount; i++)
        {//通过一个for循环来给Content下的所有子物体命名并添加委托。
            Content.GetChild(i).name = i.ToString();
            Content.GetChild(i).GetChild(0).GetComponent<Text>().text = i.ToString();
            ClickListener.Get(Content.GetChild(i).gameObject).onClick = OnBtnNumber;
        }
    }
    public void OnBtnNumber(GameObject obj)
    {
        float length = int.Parse(obj.name) * (Content.GetComponent<GridLayoutGroup>().cellSize.y + Content.GetComponent<GridLayoutGroup>().spacing.y);
        float ViewProtH=Content.childCount*(Content.GetComponent<GridLayoutGroup>().cellSize.y+Content.GetComponent<GridLayoutGroup>().spacing.y)-ViewProt.sizeDelta.y-Content.GetComponent<GridLayoutGroup>().spacing.y;
        if (length > ViewProtH)
        {
            length = ViewProtH;
        }
        DOTween.To(() => Content.offsetMax, x => Content.offsetMax = x, new Vector2(0, length), 0.615f);
    }


}

Grid Layout Group.cellSize.y的参数为Content下子物体的长度,.Spacing.y为子物体之间Y轴的间隔,因为我们用int类型给子物体命名,所以当子物体的名字乘以子物体的长度加上子物体之间的间隔就等于每个按钮应该缩进的值也就是Length变量。
然后最后几个按钮会因为缩进不够而特别鬼畜,所以我们通过计算Content的总长度减去ViewProt的长度再减去子物体之间的间隔可以得到在ViewPort里最上方的按钮应该缩进的长度。
所以当按下的按钮的缩进长度大于这个长度时,我们将ViewProt最上方按钮应缩进的长度赋给Length变量
同时调用DOTween的To方法,将Content的位置移动到Length变量。





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值