一、组件属性设置如下如图所示:
1、Sroll Rect
2、Content Size Fiter和Grid Layout Group
若content锚点为Top,有ContentSizeFitter组件,需将Honizontal Fit改为Preferred Size,使用脚本中方法一计算方式。
若content锚点为Left,有ContentSizeFitter组件,需将Honizontal Fit改为unconstrained,设置每页宽度,使用脚本中方法二计算方式。
?若无ContentSizeFitter组件,且content锚点设置为Left时,使用方法一的计算方式,需要设置总页数宽度;使用脚本中方法二的计算方式,需要设置每页宽度。
?
?二、具体代码如下(根据自己的功能需求调整代码逻辑)
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 通过ScrollView(ScrollRect)实现翻页效果
/// </summary>
public class ScrollViewTurnPages : MonoBehaviour
{
public Button nextBtn;
public Button lastBtn;
private RectTransform contents;
private ScrollRect scrollrect;
//根据需求设定
private int btnAllcount = 20;//按钮总个数
private int btnCount = 10;//每页中按钮个数
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>();
btnAllcount = contents.childCount;
#region 方法一
contentsWidth = contents.rect.width;
delta_X = Mathf.CeilToInt(btnAllcount / btnCount) * contentsWidth;
#endregion
#region 方法二
//contentsWidth = contents.sizeDelta.x;
//delta_X = Mathf.CeilToInt(btnAllcount / btnCount) * contentsWidth;//通过计算获得contents的长度
//contents.sizeDelta = new Vector2(delta_X, contents.sizeDelta.y);//给contents设定大小
#endregion
Debug.LogError(contentsWidth);
//下一页
nextBtn.onClick.AddListener(delegate
{
isRoll = true;
targePoint += 1 / (delta_X / contentsWidth - 1);
if (targePoint > 1)
targePoint = 1;
});
//上一页
lastBtn.onClick.AddListener(delegate
{
isRoll = true;
targePoint -= 1 / (delta_X / contentsWidth - 1);
if (targePoint < 0)
targePoint = 0;
});
}
private void Update()
{
//翻页
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);
}
}
}
参考博客地址:【笔记】Unity ScrollView 按钮翻页_zjh_368的博客-CSDN博客_unity按钮翻页
|