I have and array called ball[ ].
My game creates a number of gameobjects in ball[ ] and then it places them randomly in the space.
I want to find out the index of ball[ ] when I click on one of the game objects.
How can I achive that.
var newBall : GameObject = GameObject.Instantiate(ballPrefab,Vector3(random.x,random.y,0), transform.rotation);
balls[i]=newBall;
and the raycast I have returns the transform.
var ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit2 : RaycastHit;
if (Physics.Raycast(ray2, hit2, 100)){
if(Input.GetButton("Fire1")) {
targetedit=hit2.transform;
ballsid=//here I dont know how can I get the Index of balls that correspond to the target.
}
}
This may work - untested. (I flipped your conditional because its better that way.)
function Update() {
if (Input.GetButton("Fire1")) {
if (Physics.Raycast(ray2, hit2, 100)) {
try {
ballsid = System.Array.IndexOf(balls, hit.transform.gameObject);
} catch (Exception e) {
Debug.Log("Something bad happened!");
}
}
}
}
Alternately, roll your own.
// returns the index in list that test occurs or -1 if it isn't present
function IndexOf(object[] list, object test) {
for (i = 0; i < list.Length; i++) {
if (list[i] == test) {
return i;
}
}
return -1;
}