Question by
ultralink20 · Jul 01, 2017 at 07:13 AM ·
loopfreezebugs
Why does this code freeze unity?
This code is supposed to generate a random maze. Whenever I attach it to a game object and run the game, however, the entire program freezes and I have to close it from task manager. The only thing I can come up with is that it is getting stuck in an infinite loop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MazeGenerator : MonoBehaviour
{
public GameObject cubePrefab;
int width = 10;
int height = 10;
void Start ()
{
int[,] maze = new int[width, height];
for (int i =0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
maze[i, j] = 1;
}
}
maze = path(width, height, 0, 0, maze);
int[] cords = new int[2];
cords = nextPath(maze);
while(cords[0] != -1)
{
maze = path(width, height, cords[0], cords[1], maze);
cords = nextPath(maze);
}
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (maze[x,y] == 1)
{
Instantiate(cubePrefab, new Vector3(x, 0, y), Quaternion.identity);
}
}
}
}
int[,] path (int width, int height, int x, int y, int[,] maze)
{
maze[x, y] = 0;
int adjacentSpaces = 0;
while (adjacentSpaces < 2)
{
adjacentSpaces = 0;
int direction = (int)Random.value * 3;
if (direction == 0)
x--;
if (direction == 1)
{
y++;
}
if (direction == 2)
x++;
if (direction == 3)
y--;
if (x >= 0 && x < width && y >= 0 && y < height)
{
if (x - 1 >= 0)
{
if (maze[x - 1, y] == 0)
adjacentSpaces++;
}
if (y - 1 >= 0)
{
if (maze[x, y - 1] == 0)
adjacentSpaces++;
}
if (x + 1 < width)
{
if (maze[x + 1, y] == 0)
adjacentSpaces++;
}
if (y + 1 < height)
{
if (maze[x, y + 1] == 0)
adjacentSpaces++;
}
if (adjacentSpaces == 1)
{
maze[x, y] = 0;
}
}
else
adjacentSpaces = 2;
}
return maze;
}
int[] nextPath (int[,] maze)
{
int[] answer = new int[2];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int adjacentSpaces = 0;
if (x - 1 >= 0)
{
if (maze[x - 1, y] == 0)
adjacentSpaces++;
}
if (y - 1 >= 0)
{
if (maze[x, y - 1] == 0)
adjacentSpaces++;
}
if (x + 1 < width)
{
if (maze[x + 1, y] == 0)
adjacentSpaces++;
}
if (y + 1 < height)
{
if (maze[x, y + 1] == 0)
adjacentSpaces++;
}
if (adjacentSpaces == 1)
{
answer[0] = x;
answer[1] = y;
return answer;
}
}
}
answer[0] = -1;
answer[1] = -1;
return answer;
}
void Update()
{
}
}
Comment
Your answer
Follow this Question
Related Questions
Unity freezes when adding a GameObject to a List 1 Answer
Unity freezes. I dont know why... 3 Answers
loop causes freeze 0 Answers
Whole computer tanks while starting Unity games. 0 Answers
Why Unity 5 freeze when build sharedassets0.assets ? 15 Answers