I’m attempting to create an algorithm to generate a maze through recursive backtracking. I am using Random.Range to find random directions, and my program doesn’t properly function whilst I am faced with this exception:
StackOverflowException
UnityEngine.Random.Range (Int32 min, Int32 max) (at C:/buildslave/unity/build/Runtime/Export/Random.bindings.cs:48)
GenerateMaze.CarveFrom (Int32 x, Int32 y) (at Assets/Scripts/GenerateMaze.cs:75)
GenerateMaze.CarveFrom (Int32 x, Int32 y) (at Assets/Scripts/GenerateMaze.cs:136)
GenerateMaze.CarveFrom (Int32 x, Int32 y) (at Assets/Scripts/GenerateMaze.cs:136)
[continues on forever]<message truncated>
The following is my recursive function:
void CarveFrom(int x, int y)
{
cells[x, y].visited = true; // cells stored in 2D array of Cell objects, each with a 'visited' variable and x, y coordinates
stack.Add(cells[x, y]); // List<> to manage stack behavior
int dir = Random.Range(1, 5); // generates random integer read as direction, 1 being north, then clockwise respectively
bool recursed = false; // boolean to check state of execution
if (dir == 1)
{
if (y != 0)
{
Cell c = cells[x, y - 1];
if (!c.visited)
{
Destroy(c.southWall);
CarveFrom(c.x, c.y);
recursed = true;
}
}
}
if (dir == 2)
{
if (x != width - 1)
{
Cell c = cells[x + 1, y];
if (!c.visited)
{
Destroy(c.southWall);
CarveFrom(c.x, c.y);
recursed = true;
}
}
}
if (dir == 3)
{
if (y != height - 1)
{
Cell c = cells[x, y + 1];
if (!c.visited)
{
Destroy(c.southWall);
CarveFrom(c.x, c.y);
recursed = true;
}
}
}
if (dir == 4)
{
if (x != 0)
{
Cell c = cells[x - 1, y];
if (!c.visited)
{
Destroy(c.southWall);
CarveFrom(c.x, c.y);
recursed = true;
}
}
}
if (!recursed) // if not recursed, function wasnt recalled
{
if (AnyUnvisitedCells() || stack.Count != 0) // backtrack in the stack and then return to origin.
{
Cell c = stack[stack.Count - 1];
CarveFrom(c.x, c.y);
stack.RemoveAt(stack.Count - 1); // this is line 136, the line noted by the exception
}
}
}