The button in the sliding list is displayed in the center after being clicked

Example settings: (7 buttons are placed in the sliding list as an example, the number can be configured at will)
insert image description hereinsert image description hereinsert image description hereinsert image description hereScript content:

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;
    }
}

Guess you like

Origin blog.csdn.net/weixin_47819574/article/details/129419475