IndexOutOfRangeException:数组索引超出范围Unity

时间:2017-05-31 06:16:16

标签: c# multidimensional-array indexing unity2d

我正在尝试构建一个Pathfinding A *代码,但不断收到数组索引错误。我试过用x和y调整,但到目前为止没有运气。 这是代码。

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 个答案:

答案 0 :(得分:1)

您是否可以将x = -1;中的所有初始化更改为x = 0; 数组总是以零开始。