Grid generation
- Game Development course
- Advanced
- Lesson 46/71
- 4 min
Learn to generate maps with a 2D grid.
2D Grid-Based Map Generation
Many strategy, puzzle, and roguelike titles are built on a 2D Grid matrix. Initializing int[,] map = new int[width, height]; allows assigning tile identities like grass, water, or wall to each cell.
int[,] map = new int[10, 10];
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
map[x, y] = 1; // 1 = Ground tile
}
}Nested for loops iterate across coordinates to generate the matrix layout.
Tile and Prefab Instantiation
Once the grid array is resolved, visual prefabs are spawned matching cell indices. Cell coordinates are scaled by tileSize to derive world positions.
Vector3 pos = new Vector3(x * tileSize, 0, y * tileSize);
Instantiate(tilePrefab, pos, Quaternion.identity);This materializes the numeric memory matrix into an interactable world map.
Practice Grid size configuration
Define a Start method. Inside, declare int gridBoyut = 16; and print "Grid boyutu: " + gridBoyut to the console.
Starter code
using UnityEngine;
public class GridTester : MonoBehaviour
{
// Start icinde gridBoyut tanimla ve yazdir
}Sample solution
using UnityEngine;
public class GridTester : MonoBehaviour
{
void Start()
{
int gridBoyut = 16;
Debug.Log("Grid boyutu: " + gridBoyut);
}
}Expected output
Grid boyutu: 16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which data structure is best suited to store the tile type at each (x, y) cell coordinate on a 2D grid map?
- TextMeshPro font asset
- Rigidbody component
- AudioSource array
- Two-dimensional array (int[,]) Correct answer
Explanation: Two-dimensional arrays (int[,]) natively represent row-and-column coordinates for grid cells.
2 Allocate grid matrix
int[,] gridMap = new int[____, height];
int[,] gridMap = new int[width, height];
Explanation: When defining a 2D grid array, the first dimension conventionally represents the width.
3 Grid map components
| Term | Meaning |
|---|---|
Grid |
Cellular grid made of rows and columns |
Tile |
Tile piece placed into a grid cell |
int[,] |
Two-dimensional matrix data structure |
tileSize |
Physical distance spacing between cells |