示例设置:(滑动列表中放了7个按钮作为示例,数量可以随意配置)
脚本内容:
using UnityEngine;
using UnityEngine.UI;
public class MTest : MonoBehaviour
{
public RectTransform rec;
public ScrollRect scrollRect;
public int count = 7;
public Button[] btns = new Button[7];
public RectTransform btnRec;
//按钮长度
float itemWidth;
//水平组件
public HorizontalLayoutGroup hlGroup;
//中间间隔长度
float middleWidth;
//左间隔
float leftWidth;
//右间隔
float rightWidth;
//显示长度
float showWidth;
private void Awake()
{
itemWidth = btnRec.rect.width;
middleWidth = hlGroup.spacing;
leftWidth = hlGroup.padding.left;
rightWidth = hlGroup.padding.right;
showWidth = rec.rect.width;
btns[0].onClick.AddListener(() => OnClickBtn(0));
btns[1].onClick.AddListener(() => OnClickBtn(1));
btns[2].onClick.AddListener(() => OnClickBtn(2));
btns[3].onClick.AddListener(() => OnClickBtn(3));
btns[4].onClick.AddListener(() => OnClickBtn(4));
btns[5].onClick.AddListener(() => OnClickBtn(5));
btns[6].onClick.AddListener(() => OnClickBtn(6));
}
public void OnClickBtn(int index)
{
//总滑动长度
//所有按钮长度 + 所有中间间隔长度 + 左边距离+ 右边距离 - 显示长度
float allLength = itemWidth * count + middleWidth * (count - 1) + leftWidth + rightWidth - showWidth;
//当前按钮总间隔长度
//(一个按钮长度 + 一个间隔长度) * 当前按钮序号 + 一半按钮长度
float simpleLength = (itemWidth + middleWidth) * index + itemWidth / 2;
//所需移动的长度
//左间隔 + 总间隔长度 - 一半显示距离
float moveLength = leftWidth + simpleLength - showWidth / 2;
//转成滑块位置 0~1
float value = Mathf.Clamp(moveLength / allLength, 0f, 1f);
scrollRect.horizontalNormalizedPosition = value;
}
}