【笔记】Unity ScrollView 按钮翻页

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

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 float targePoint;
    private int count = 12;//按钮总个数
    private float delta_X ;
    private bool isRoll; //是否翻页

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

        //通过计算获得contents的长度(400为一页的长度)
        delta_X = Mathf.CeilToInt(count / 6) * 400f;
        //给contents设定大小
        contents.sizeDelta = new Vector2(delta_X, contents.sizeDelta.y);
        //给contents添加按钮
        for (int i = 0; i < count; 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 / 400f - 1);
            if (targePoint < 0)
                targePoint = 0;
            
        }
        //右按钮
        if (GUI.Button(new Rect(420, 80, 100, 30), "下一页"))
        {
            isRoll = true;
            targePoint += 1 / (delta_X / 400f - 1);
            if (targePoint > 1)
                targePoint = 1;

        }

        //翻页
        if (isRoll)
        {
            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);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章