上图释:通过代码生成按钮,一页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);
}
}
}