(转载)Unity 关于动态监听时,点击Button,返回其在数组中的下标

其实是绕了一圈,把数组里的元素放进数组列表里再读取它的下标

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

public class AddListener : MonoBehaviour {

    public GameObject[] arrayButton;//存放按钮的数组
    private ArrayList listButton;//存放按钮的数组列表

    private GameObject temporaryBtn;//临时放存放单个按钮
    private int buttonNum;
	// Use this for initialization
	void Start () {
        listButton = new ArrayList(arrayButton);
        foreach (GameObject btn in arrayButton)
        {
            btn.GetComponent<Button>().onClick.AddListener(delegate () { ShowNumber(); });
        }
    }

    public void ShowNumber()
    {
        temporaryBtn = EventSystem.current.currentSelectedGameObject;//获取被点击的物体,注意要引用using UnityEngine.EventSystems;
        buttonNum = listButton.IndexOf(temporaryBtn);//读取这个OBJ在数组列表中的位置(下标)
        Debug.Log(buttonNum);
        temporaryBtn = null;
    }
}

设置:

下面是运行结果:

 

---------------------
作者:三十五分02
来源:CSDN
原文:https://blog.csdn.net/lzb_ide/article/details/81347955

posted @ 2019-03-26 20:42  vuciao  阅读(648)  评论(0编辑  收藏  举报