【笔记】Unity ScrollView 按钮翻页

上图释:通过代码生成按钮,一页6个按钮,左右切换翻页。

上图释:添加GridLayoutGroup组件可以自动排列元素(另外有平行垂直排序组件HorizontalLayoutGroup ,VerticalLayoutGroup),通过调整属性可以调节排列间距。上图400为一页的宽度,200是单列元素所占页面宽度,因为我的案例是2列按钮,所以该单列元素宽度的倍数必须得等于一页的宽度,否则会出现类似翻页不足或超出的现象。

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

public class TestScroolView : MonoBehaviour {

    public GameObject objBtn;

    private RectTransform contents;
    private ScrollRect scrollrect;

   //根据需求设定
    private int btnAllcount = 12;//按钮总个数
    private int btnCount = 6;//每页中按钮个数

    private float contentsWidth;
    private float delta_X;
    private float targePoint;
    private bool isRoll; //是否翻页

    void Start()
    {
        contents = transform.Find("Viewport/Content") as RectTransform;
        scrollrect = transform.GetComponent<ScrollRect>();

        contentsWidth = contents.sizeDelta.x;
        //通过计算获得contents的长度
        delta_X = Mathf.CeilToInt(btnAllcount / btnCount) * contentsWidth;
        //给contents设定大小
        contents.sizeDelta = new Vector2(delta_X, contents.sizeDelta.y);
        //给contents添加按钮
        for (int i = 0; i < btnAllcount; i++)
        {
            GameObject obj = Instantiate(objBtn, contents);
            //obj.transform.GetChild(0).GetComponent<Text>().text = i.ToString();
        }
    }

    private void OnGUI()
    {
        //左按钮
        if (GUI.Button(new Rect(200, 80, 100, 30), "上一页"))
        {
            isRoll = true;
            targePoint -= 1 / (delta_X / contentsWidth - 1);
            if (targePoint < 0)
                targePoint = 0;

        }
        //右按钮
        if (GUI.Button(new Rect(420, 80, 100, 30), "下一页"))
        {
            isRoll = true;
            targePoint += 1 / (delta_X / contentsWidth - 1);
            if (targePoint > 1)
                targePoint = 1;

        }

        //翻页
        if (isRoll)
        {
            print("翻页");
            if (Mathf.Abs(scrollrect.horizontalNormalizedPosition - targePoint) < 0.01f)
            {
                scrollrect.horizontalNormalizedPosition = targePoint;
                isRoll = false;
                return;
            }
            //设置水平滚动位置
            scrollrect.horizontalNormalizedPosition = Mathf.Lerp(scrollrect.horizontalNormalizedPosition, targePoint, Time.timeScale * 0.1f);
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值