ArgumetnOutOfRangeException: Index was out of range.

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 :slight_smile:
P.S great tutorial

Hello, you have omitted some key information from your error message. Every error message contains a filename and line number of the error. Please give the full error message as it shows in your inspector window. It will make it easier to help you.

1 Like

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is and what line of code accesses it <— critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection size
  • remember you might have more than one instance of this script in your scene/prefab
  • remember the collection may be used in more than one location in the code
  • remember that indices start at ZERO (0) and go to the count / length minus 1 (three (3) items are 0,1,2 only)
1 Like

Thank you for help! I very apreaciate you spent your time looking at my code :]

Thank you for looking at my code and helping :] Here’s full error message

[19;29;37] ArgumentOutOffRangeExeptation: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name Index

Oh and here’s photo

Looking at the above code, it has many places where it blindly accesses collections via a computed index.

Anywhere you see square brackets such as [ and ] it is accessing a collection.

In many places it appears to access these values with very complex expressions, and does not ensure they are between 0 and the size minus one.

Examples are here:

These are likely to be problematic.

It is always better to compute the index value and check it before using it.

Other places include the two different dereferences here:

Is currentCell between zero and the board length?

Is status at least 2 items long?

etc.

1 Like

Thank you for lots of help! now I’m probably know how it work :wink: