- Home /
Find a game object using the value of a variable in the script attached to it, or with it's transform.position?
I have grid of instantiated objects, each with a script attached that contains a Vector2 defining the grid position (i.e. x,y). Is it possible to access the game object only by knowing the Vector2 grid coordinates?
It would be very useful to me to be able to send values to functions attached to each object in the grid, based on where it is in that grid.
I have a simple function to convert my grid coordinates into the transform.position of the center of each grid square. I was thinking that one option would be to instantiate an empty object with collider at the transform.position of the grid square in question, and use the hit to return the game object, but I wondered if there may be a more efficient way since this may need to be carried out a at a relatively fast rate.
Answer by theundergod · Feb 24, 2013 at 12:37 AM
You could also create a 2-dimensional array with the size of said grid and when instantiating the objects assign them to the appropriate position in the array.
int xSize = 10;
int ySize = 20;
GameObject[,] gridObjects = new GameObject[xSize, ySize];
GameObject newObject = (GameObject)Instantiate (prefab, vector3Position, quaternionRotation);
ScriptWithVector2 script = newObject.GetComponent<ScriptWithVector2>();
gridObjects[script.vector2.x, script.vector2.y] = newObject;
Then all you would need to is use: gridObjects[yourVector2.x, yourVector2.y]
To get the desired GameObject.
Or obviously a variation of the above, but I think it gets the point across.
Thanks, I used this principle in the end. I stored the game objects in an array, and I can access that or any of the scripts attached to each game object as and when I need to. If I have any performance issues with using GetComponent's (hopefully not, it's a pretty slow paced turn game), then I can revisit this and look at caching the relevant scripts too.
Answer by RetepTrun · Feb 24, 2013 at 12:29 AM
Perhaps collect everybody's transform.position in an array or list and then use a foreach loop to compare the positions to the vector3 equivalent of those vector2's.
Or raycast up from each grid square and see if you hit anything
Thanks. I think this would work in other circumstances. I actually opted to collect all the game objects in an array (as per theundergod's suggestion) with the same i & j coordinates. I did that because there were multiple scripts attached to each object that I would like to be able to access.