Skip to content

Instantly share code, notes, and snippets.

@ShuraProgerMain
Created August 10, 2025 10:31
Show Gist options
  • Save ShuraProgerMain/d54a6a3ab7c8486985ce2202b34d394a to your computer and use it in GitHub Desktop.
Save ShuraProgerMain/d54a6a3ab7c8486985ce2202b34d394a to your computer and use it in GitHub Desktop.
Search index in grid under mouse
using UnityEngine;
using UnityEngine.UI;
public class CellIndexSearcher
{
private readonly RectTransform _cellsContainer;
private readonly float _cellW;
private readonly float _cellH;
private readonly float _spaceX;
private readonly float _spaceY;
private readonly int _rowCount;
private readonly int _columnCount;
public CellIndexSearcher(RectTransform cellsContainer, GridLayoutGroup grid, int rowCount, int columnCount)
{
_cellsContainer = cellsContainer;
_cellW = grid.cellSize.x;
_cellH = grid.cellSize.y;
_spaceX = grid.spacing.x;
_spaceY = grid.spacing.y;
_rowCount = rowCount;
_columnCount = columnCount;
}
public (int row, int column) GetCellIndexUnderMouse(Vector2 mousePosition)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
_cellsContainer, mousePosition, null, out Vector2 localPoint))
{
int column = -(Mathf.FloorToInt(-localPoint.x / (_cellW + _spaceX)) - 3);
int row = -(Mathf.FloorToInt(localPoint.y / (_cellH + _spaceY)) - 3);
if (row >= 0 && row < _rowCount &&
column >= 0 && column < _columnCount)
{
return (row, column);
}
}
return (-1, -1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment