Find the array index of and array of gameobjects

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;
}
1 Like

I would put a variable on the ball gameobject that is set to its index number at creation and then just query for that variables value.

So

Create Ball
Add Ball to array
Set Ball’s variable to array length -1

profit.

So long as you’re not modifying the array or you ensure you keep the array and variables in sync.

Um, why not use a List object.

Create a ball, add it to a list

Use List.IndexOf(object) and you get a number

profit. lol

As well, you can use List.Remove or List.RemoveAt to remove null objects to keep your list clean.

I prefer BigMisterB’s profit

How about a dictionary?

Dictionary<GameObject, int>