IndexOutOfRangeException: индекс массива выходит за пределы диапазона Unity

Я пытался создать код Pathfinding A*, но получаю ошибку Array Index. Я пытался настроить х и у, но пока не повезло. Вот код

public int columns = 9;                                                      //Columns and rows to set up the board
public int rows = 9;                                                //This number are the usable tiles, the complete board is 11 by 11
                                                                    //With a border of 1 tile

public Node[,] graph;

//Class Node
public class Node
{
    public List<Node> neighbours;                                                   //List of all the neighbours nodes (4Directions)

    public Node()
    {
        neighbours = new List<Node>();
    }
}

//Sets up the outer walls and floor (background) of the game board.
void BoardSetup()
{
    for (int x = -1; x < columns + 1; x++)
    {
        for (int y = -1; y < rows + 1; y++)
        {
            Edited out Code, don't think has anything to do with my problem.
        }
    }
}

//Creates the graph to use Pathfinding
void GeneratePathfindingGraph()
{
    //Create graph
    graph = new Node[columns, rows];

    for (int x = -1; x < columns + 1; x++)
    {
        for (int y = -1; y < rows + 1; y++)
        {

            graph[x, y] = new Node();

            Add the 4 cardinal adjacent tiles
            if (x != - 1)
                graph[x, y].neighbours.Add(graph[x - 1, y]);      
            if (x != columns - 1)
                graph[x, y].neighbours.Add(graph[x + 1, y]);       //Where I am getting the error
            if (y != - 1)
                graph[x, y].neighbours.Add(graph[x, y - 1]);
            if (y != rows - 1)
                graph[x, y].neighbours.Add(graph[x, y + 1]);
        }
    }
}

//SetupScene initializes our level and calls the previous functions to lay out the game board
public void SetupScene(int level)
{
    //Creates the outer walls and floor.
    BoardSetup();

    //Creates the Node map to use Pathfinding
    GeneratePathfindingGraph();
}

}

Я отредактировал большую часть кода в этом классе, я не думаю, что это имеет непосредственное отношение к проблеме.

1 ответ

Решение

Можете ли вы изменить все инициализации в цикле, как x = -1;в x = 0;Массивы всегда начинаются с нуля.

Другие вопросы по тегам