C# IndexOutOfRangeException:数组索引超出范围
我试图构建一个路径查找a*代码,但不断得到一个数组索引错误。我试过用x和y来调整,但到目前为止运气不好。 这是代码C# IndexOutOfRangeException:数组索引超出范围,c#,multidimensional-array,indexing,unity2d,C#,Multidimensional Array,Indexing,Unity2d,我试图构建一个路径查找a*代码,但不断得到一个数组索引错误。我试过用x和y来调整,但到目前为止运气不好。 这是代码 public int columns = 9; //Columns and rows to set up the board public int rows = 9; //This n
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();
}
public int columns=9//用于设置板的列和行
公共整数行=9//这个数字是可用的瓷砖,整个板是11乘11
//有1块瓷砖的边框
公共节点[,]图;
//类节点
公共类节点
{
公共列表邻居;//所有邻居节点的列表(4个方向)
公共节点()
{
邻居=新列表();
}
}
//设置游戏板的外墙和地板(背景)。
void BoardSetup()
{
对于(int x=-1;x
}
我已经编辑掉了这个类中的大部分代码,我认为这与问题没有多大关系。你能像
x=-1代码>至x=0代码>
数组总是以零开始。循环中的int x=-1
有什么具体原因吗?为什么循环从-1
开始。请注意,if
s始终只检查一个变量(x
或y
),因此在第一次迭代中,您肯定会遇到一个图[-1,-1]
<代码>-1
不是数组的有效索引。从0
开始循环,它应该可以正常工作(假设剩下的算法是正确的,我没有检查)。if(x!=columns-1)//graph[x,y].neights.Add(graph[x+1,y])代码>x
=-1,列-1
=8。您可以尝试访问图形[-1,-1]
,这是不可能的,因为每个索引都从0开始。谢谢大家!我不知道每个索引都必须从0开始。