Im trying to figure out why my code isn’t generating the other two walls I need some help
this is the code i have:
using System.Collections.Generic;
using UnityEngine;
public class SimpleMazeBuilder : MonoBehaviour
{
[Header(“Prefab + Grid Settings”)]
public GameObject wallPrefab;
public int width = 51; // Must be odd numbers
public int height = 51; // Must be odd numbers
public float spacing = 1f;
private int[,] maze;
void Start()
{
GenerateMaze();
DrawMaze();
}
void GenerateMaze()
{
maze = new int[width, height];
// Create entrance and exit
maze[0, 1] = 0; // Entrance (left side, near top)
maze[width - 1, height - 2] = 0; // Exit path (inner cell)
maze[width - 1, height - 1] = 0; // Clear bottom-right corner
// Fill everything with walls
for (int x = 1; x < width - 1; x++)
for (int y = 1; y < height - 1; y++)
maze[x, y] = 1;
// Carve maze starting from entrance
Carve(1, 1);
}
void Carve(int x, int y)
{
maze[x, y] = 0;
List<Vector2Int> directions = new List<Vector2Int>
{
new Vector2Int(2, 0),
new Vector2Int(-2, 0),
new Vector2Int(0, 2),
new Vector2Int(0, -2)
};
Shuffle(directions);
foreach (Vector2Int dir in directions)
{
int nx = x + dir.x;
int ny = y + dir.y;
if (IsInBounds(nx, ny) && maze[nx, ny] == 1)
{
maze[x + dir.x / 2, y + dir.y / 2] = 0;
Carve(nx, ny);
}
}
}
void DrawMaze()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (maze[x, y] == 1)
{
Vector3 pos = new Vector3(x * spacing, y * spacing, 0);
Instantiate(wallPrefab, pos, Quaternion.identity);
}
}
}
Debug.Log("Maze built with entrance and exit.");
}
void Shuffle(List<Vector2Int> list)
{
for (int i = 0; i < list.Count; i++)
{
Vector2Int temp = list[i];
int rand = Random.Range(i, list.Count);
list[i] = list[rand];
list[rand] = temp;
}
}
bool IsInBounds(int x, int y)
{
return x > 0 && x < width - 1 && y > 0 && y < height - 1;
}
}
this is the result

