# Index 2D array using this.gameObject and OnMouseDown

Hello,

In a previous version of my game I had tiles instantiated using a grid and gave them the name of their coordinates. Like 13 would be in x=1 and y=3. This enabled me to keep track of the objects. I needed to change the object clicked on and the one above so I could simply get the name of the object clicked on, increase the y value and look for that object.

This was however not a nice way to do this (first game), so I started looking at better ways to keep track of these instantiated objects. The way I have it now is that they are put in a 2d array (array[,]). However I was assuming I could simply get the index of the object in the array by some magic function. This does not seem to be the way for 2D arrays right? “Array.IndexOf” only seems to work for 1D arrays.

Is there a good way to do this? Or should I do a double for loop again, basically almost being back this more devious method?

There is no 2d indexOf method
You would need to double loop to search it.
You could still use some technique to store an objects index so that you can use the Array, perhaps by using it’s name, or attaching a component that stores it’s 2d index, or using a Dictionary to look up indices:

``````class Coord { public int x, y }
Dictionary <GameObject, Coord> lookUp;
GameObject[,] map;

//on Mouse down
Coord myCoord = lookUp[clickedGameobject]
GameObject above = map[myCoord.x, myCoord.y+1];
``````

Assuming a uniform grid, you can divide their positions to find their index.

``````// Assuming we have a Transform called tile:
int indexX = tile.position.x / GridWidth;
int indexY = tile.position.y / GridHeight;
``````