【Unity随手记】在Button列表中获取当前按钮索引编号

        随手记一些容易忘记的代码,方便以后回顾:将button拉入列表中,选中按钮输出该按钮在列表中的索引编号。

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ButtonListIndex : MonoBehaviour
{
    public List<GameObject> buttonList = new List<GameObject>();
    private int buttonNum;

    private void Start()
    {
        foreach (GameObject go in buttonList)
        {
            go.GetComponent<Button>().onClick.AddListener(delegate ()
            {
                OnClick();
            });
        }
    }

    //获取当前按钮列表索引编号
    void OnClick()
    {
        buttonNum = buttonList.IndexOf(EventSystem.current.currentSelectedGameObject);
        Debug.Log(buttonNum);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45360148/article/details/130931890