Do you see any errors here? Cuz while loop ends even if the current not equals to the end.
using UnityEngine;
using System.Collections.Generic;
[RequireComponent(typeof(NodeGenerator))]
public class PathGenerator : MonoBehaviour
{
int maxNodesInARow;
Cell current;
Cell[,] grid;
Stack<Cell> stack;
void Start()
{
maxNodesInARow = GetComponent<NodeGenerator>().amountOfNodesInARow;
grid = new Cell[maxNodesInARow, maxNodesInARow];
stack = new Stack<Cell>();
for (int x = 0; x < maxNodesInARow; x++)
{
for (int y = 0; y < maxNodesInARow; y++)
{
grid[x, y] = new Cell(x, y);
if (x == 0 || y == 0 || x == maxNodesInARow - 1 || y == maxNodesInARow - 1)
grid[x, y].visited = true;
}
}
// Make the initial cell the current cell and mark it as visited
current = grid[1, 1];
current.visited = true;
CreatePath();
foreach(Cell cell in stack)
{
NodeGenerator.nodes[cell.x, cell.y].GetComponent<Renderer>().material.color = Color.red;
}
}
void CreatePath()
{
Cell end = new Cell(maxNodesInARow - 2, maxNodesInARow - 2);
NodeGenerator.nodes[end.x, end.y].GetComponent<Renderer>().material.color = Color.black;
while (current.x != end.x && current.y != end.y) // While haven't reached the end
{
Cell next = current.GetNeighbor(grid); // Choose randomly one of the unvisited neighbours
if (next != null) // If the current cell has any neighbours which have not been visited
{
stack.Push(current); // Push the current cell to the stack
// Make the chosen cell the current cell and mark it as visited
for(int i = 0; i < maxNodesInARow; i++)
{
bool found = false;
for (int j = 0; j < maxNodesInARow; j++)
{
if (grid[i, j] == next)
{
found = true;
current = grid[i, j];
break;
}
}
if (found)
break;
}
current.visited = true;
}
else if (stack.Count != 0) // Else if stack is not empty
{
current = stack.Pop();
}
}
}
class Cell
{
public int x;
public int y;
public bool visited;
public Cell(int x, int y)
{
this.x = x;
this.y = y;
visited = false;
}
public Cell(int x, int y, bool visited)
{
this.x = x;
this.y = y;
this.visited = visited;
}
public Cell GetNeighbor(Cell[,] grid)
{
List<Cell> neighbors = new List<Cell>();
int maxNodesInARow = grid.GetLength(0);
Cell top = grid[x, y + 1];
Cell right = grid[x + 1, y];
Cell bottom = grid[x, y - 1];
Cell left = grid[x - 1, y];
Cell end = new Cell(maxNodesInARow - 2, maxNodesInARow - 2);
if (top != null && !top.visited)
{
neighbors.Add(top);
}
if (right != null && !right.visited)
{
neighbors.Add(right);
}
if (bottom != null && !bottom.visited)
{
neighbors.Add(bottom);
}
if (left != null && !left.visited)
{
neighbors.Add(left);
}
if (neighbors.Count > 0) // If there's any neighbors
{
for (int i = 0; i < neighbors.Count; i++) // Return end if can go there
{
if (neighbors_.x == end.x && neighbors*.y == end.y)*_
return neighbors*;*
}
int random = Random.Range(0, neighbors.Count);
return neighbors[random];
}
return null;
}
}
}
[76601-wtf.png|76601]