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.
@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.
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
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>();
}