Button number...

Suppose I have an array of many buttons, for example, 15. I need to get the number of the button in the array when I press it. How to do it? The name of the button array is “Load Button”, and the name of the function when you click “ID Check Function”.

For every array (regardless if it stores buttons, strings, integers, or anything else) you have the property Length, which will return the size (number of items) of the array.
Note that if some entries of the array are null it would still count it.
Often it is easier and better to use List instead which has a property Count (not Length).

Well, I know these functions and what they give me. They do not solve the problem.

Then describe your problem better.

You can use IndexOf to get the index of the object in the array/list.

The other way is to simply loop through the collection in a for loop and do some sort of comparison and once you get a match, return the value in your for loop.

using UnityEngine;
using UnityEngine.UI;

public class MyButton : MonoBehaviour
{
    [SerializeField]
    public int thisButtonsIndex;
    Button thisButton;

    void Start ()
    {
        thisButton = gameObject.GetComponent<Button> ();
        thisButton.onClick.AddListener (Handle_Click);
    }

    void Handle_Click ()
    {
        Debug.Log (thisButtonsIndex);
    }
}

Assign a button script to your buttons and give their index through inspector.

Ok, now I understand what you want to achieve (didn’t read carefully enough at the first place).
If you assign the callbacks via script you can use lambda expressions:

[SerializeField]
List<Button> _buttons = new List<Button>();

void Start()
{
    for(int i = 0; i < _buttons.Count; i++)
    {
        int cacheIndex = i; // we have to cache i to have the right value in the anonymous method
        buttons[i].onClick.AddListener(() => ButtonClicked(cacheIndex));
    }
}

void ButtonClicked(int index)
{
    // do something with the index
}
1 Like