Drawing grid on the terrain is used in lot of game genres – RTS, Simulation, Tower defense, etc. It can be done very easily in Unity.
Here is some very simple extensible solution with following features:
Respect terrain height
Option to have different texture in different parts (eg. to distinguish free and taken cells)
Configurable (you can resize grid in editor or real-time and set cell size)
Because we want to have different kind of cells we have two options – one is using separate game object for every cell and second option is using one game object containing mesh with lot of submeshes. I chose first option because of simplicity and flexibility.
For every cell we create corresponding mesh. In example above you can see that it’s very simple square mesh from just 2 triangles (line 131). Y coordinate of each square’s vertex is calculated by doing raycast on the terrain (precalculated for every cell in UpdateHeights method every frame) and adding yOffset value. For better result you can experiment with square mesh with much more triangles (eg. 24).
To every mesh of the cell we assign material based on IsCellValid method which is doing raycast through the center of the cell and checking “Buildings” layer for some colliders, if there is any the cellMaterialInvalid is used (red in screenshot), otherwise cellMaterialValid is used (green).
Number of cells are managed in UpdateSize method which is checking for size changes and doing corresponding action – adding new or deleting cells.
In method UpdatePosition the grid is moved so it’s center is always under mouse cursor.
This is just an example and for real use you will probably have to modify position and resizing behaviour.