Getting the x and y coordinates of an image in a GridLayoutGroup

I have a large GridLayoutGroup, but I’m really struggling to accurately get the x and y position of objects in it using maths, and I’m wondering if there’s not some method in GridLayoutGroup I’m missing that can just give me the answer. Anybody know?

If not, I’m trying to work it out from GetSiblingIndex, but I’m not having much luck. With this example I get a divide by zero error. I’m kinda new to % so I’m not sure what I’m doing wrong. Height in this example can be 5, 10, or 20.

int index = hit.GetSiblingIndex();
int y = index / heightOfGrid;
int x = index % y;
return new Vector2Int(x, y);

I think I need to (at the very least) make sure the y always rounds down - but I’m trying to at least get it to roughly work first, before I add more code. It’s very I can’t find anything on this online. Somebody must have had this issue before.

Just put a little MonoBehaviour on each cell that contains public x,y integers.

You can use GetComponent() to retrieve it.

I’ve been trying to avoid that as it seems really inefficient. Working it out mathematically seems like the better open. Especially as my game grows.

To get the x coordinate, you take the modulo of the index and the height of the grid, not the y coordinate. In your code, if y is 0, you get a division by zero error, and if it’s not, you get a wrong value. heightOfGrid must also be an Integer.

int index = hit.GetSiblingIndex();
int y = index / heightOfGrid;
int x = index % heightOfGrid;
return new Vector2Int(x, y);

The operations depend on which way you read your grid. The above code assumes a left-to-right approach (columns first, rows second).

1 Like

Thank you, but it doesn’t seem to be working. No matter where I click, I get position (0, 4).

9211188--1285503--upload_2023-8-11_16-46-0.png

This code…

… obviously assumes hit is hitting a unique Transform within the grid.

What are you hitting?

It also obviously requires that you have filled each cell with something that can be hit by the graphic raycasting system in the first place.

Keep in mind that the graphics raycasting system is usually implemented through the IPointer callbacks. It is certainly not the Physics2D raycasting and not the 3D raycasting either.

… but it has the important advantage that it will Just Work™. :slight_smile:

It would, but I feel I owe my players more than that. But thank you,

I’ve just realised that my test code, which colours the tiles, didn’t fire the raycast that refreshes the hit object. Meaning it was relying on old data. The thing is finally working properly. Thank you both.

2 Likes