Hello, i’m new in unity and decide to make “RandomDungeon generator” from this tutorial
.
and get the error “ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection Parameter name: index”
I was checking a code many times but stil don’t get it.
Thanks for help and sorry if I make an language mistake (I’m not the best at eanglish).
Here’s my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DungeonGenerator : MonoBehaviour
{
public class Cell
{
public bool visited = false;
public bool[] status = new bool[4];
}
public Vector2 size;
public int startPos = 0;
public GameObject room;
public Vector2 offset;
List<Cell> board;
void GenerateDungeon()
{
for(int i = 0; i < size.x; i++)
{
for(int j = 0; j < size.y; j++)
{
var newRoom = Instantiate(room, new Vector3(i*offset.x,0,-j*offset.y), Quaternion.identity, transform).GetComponent<RoomBehaviour>();
newRoom.UpdateRoom(board[Mathf.FloorToInt(i+j*size.x)].status);
newRoom.name += " " + i + "-" + j;
}
}
}
void Start()
{
MazeGenerator();
}
void MazeGenerator()
{
board = new List<Cell>();
for (int i = 0; i < size.x; i++)
{
for (int j = 0; j < size.y; j++)
{
board.Add(new Cell());
}
}
int currentCell = startPos;
Stack<int> path = new Stack<int>();
int k = 0;
while(k < 1000)
{
k++;
board[currentCell].visited = true;
List<int> neighbors = CheckingNeighbors(currentCell);
if (neighbors.Count == 0)
{
if(path.Count == 0)
{
break;
}
else
{
currentCell = path.Pop();
}
}
else
{
path.Push(currentCell);
int newCell = neighbors[Random.Range (0, neighbors.Count)];
if(newCell > currentCell)
{
if(newCell - 1 == currentCell)
{
board[currentCell].status[2] = true;
currentCell = newCell;
board[currentCell].status[3] = true;
}
else
{
board[currentCell].status[1] = true;
currentCell = newCell;
board[currentCell].status[0] = true;
}
}
else
{
if(newCell + 1 == currentCell)
{
board[currentCell].status[3] = true;
currentCell = newCell;
board[currentCell].status[2] = true;
}
else
{
board[currentCell].status[0] = true;
currentCell = newCell;
board[currentCell].status[1] = true;
}
}
}
}
GenerateDungeon();
}
void Update()
{
}
List<int> CheckingNeighbors(int cell)
{
List<int> neighbors = new List<int>();
if (cell - size.x >= 0 && !board[Mathf.FloorToInt(cell - size.x)].visited)
{
neighbors.Add(Mathf.FloorToInt(cell - size.x));
}
if (cell + size.x < board.Count && !board[Mathf.FloorToInt(cell + size.x)].visited)
{
neighbors.Add(Mathf.FloorToInt(cell + size.x));
}
if ((cell+1) % size.x != 0 && !board[Mathf.FloorToInt(cell + size.x)].visited)
{
neighbors.Add(Mathf.FloorToInt(cell +1));
}
if (cell % size.x != 0 && !board[Mathf.FloorToInt(cell - size.x)].visited)
{
neighbors.Add(Mathf.FloorToInt(cell -1));
}
return neighbors;
}
}
One more time thanks
P.S great tutorial