【筆記】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);
        }
    }
}

 

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