The easiest way to reference your grid in code is to use a grid behaviour – a component attached to the grid builder.
To make a grid behaviour, make a new component that extends from GridBehaviour. You need to specify two type parameters:
- The first type parameter can be one of int, GridPoint2 or GridPoint3 depending on whether you have a 1D, 2D or 3D grid.
- The second type parameter depends on whether you have a tile grid (grid where each cell is a separate game object, such as a sprite or mesh) or a mesh grid (where the entire grid is a single mesh). The two options are TileCell and MeshCell.
You can override the OnInit method to perform actions just after the grid has been built. This is useful for additional initialization steps (on particular, to initialize your cells).
You can access the grid data structure, the grid map, and the grid builder through the properties Grid, GridMap, and GridBuilder.
Because the grid contains cells of type TileCell, you usually want to make a copy of the grid with a more specific type (most often, your own cell type).
Here is how to do it:
IGrid<GridPoint2, MyCell> myGrid = Grid.CloneStructure(p => Grid[p].GetComponent);
This assumes that your cell prefab has the additional MyCell component attached. You only have to do it once, so make it a field so that you can also access it from other methods, and initialize it in the OnInit method.
The GridBehaviour is also a convenient place to handle mouse input to the grid (such as clicks).
To make your grid interactable, it is necessary to add a GridEventTrigger on the same object as your grid builder. This component allows you to configure which methods should be called (on which components). It is best to define those methods in a grid behaviour, so that you have easy access to the grid, and link them in on the event trigger.
The GridEventTrigger also has a MousePosition property that always has the current mouse position in grid coordinates. You should always check whether this point is actually in your grid before using it.