Check any index of an array

I couldn’t choose a better title for this, but here is what I’m aiming for:

I have several buttons attached to a Transform array. I basically want to check if the player clicked (or tapped on an android) on any button of it and return the index of that button in the array.

I’d do a raycast from the camera to the world (Camera.ScreenPointToRay), check if anything is hit, get the transform component from that, iterate over the array and check if the object hit is in the array.

If each of your buttons is a separate game object with a collider then you could just use OnMouseDown to detect clicks:

Afaik this will work with 2D colliders as well.

@numberkrucher: This is not what I’m asking for. I need precisely know how to detect if the object is a part of an array, and also return the index of that array.

If OnMouseDown occurs for your button just check to see if it is part of your array…

With native arrays:

private void OnMouseDown() {
    if (System.Array.IndexOf(yourArray, transform) != -1) {
        // Yup, part of array...
    }
}

With generic lists:

private void OnMouseDown() {
    if (yourList.Contains(transform)) {
        // Yup, part of list...
    }
}

What about returning the index of the clicked/tapped (or target) object?

Debug.Log(IndexOf(yourArray); ? maybe, some version of that might do the trick after the if test. As you have no code to show for its pretty hard to reply to something :slight_smile:

Edit: Might need Debug.Log(Array.IndexOf(yourArray);

You can get the array index as I demonstrated; you just need a local variable.

Native array:

private void OnMouseDown() {
    int index = System.Array.IndexOf(yourArray, transform);
    if (index != -1) {
        // Yup, part of array...
        Debug.Log("The index was " + index);
    }
}

Generic list:

private void OnMouseDown() {
    int index = yourList.IndexOf(transform);
    if (index != -1) {
        // Yup, part of array...
        Debug.Log("The index was " + index);
    }
}

If your array/list is part of a parent game object then you will probably want to access it like shown below since this will make it easy for each button to access your list.

private void OnMouseDown() {
    var yourComponent = transform.parent.GetComponent<YourComponent>();
    var yourList = yourComponent.someList;

    int index = yourList.IndexOf(transform);
    if (index != -1) {
        // Yup, part of array...
        Debug.Log("The index was " + index);
    }
}

Where YourComponent could be defined something like this:

public class YourComponent : MonoBehaviour {
    public List<Transform> someList = new List<Transform>();
}