2016-04-27 25 views
2

我正在嘗試在C#中編寫Unity中的戰術RPG,並且要這樣做,我需要使用尋路,Dijkstra,節點邊緣等。 我試圖將2D區域字符代表我的節點的2D面積邊緣的地圖,這裏的地圖:2D區域中的未知字符

map

#在這裏紀念地圖的邊界和閃避的指數超出範圍的錯誤。

下面是該項目的代碼:

public Nodes[,] GenerateNodes(TextAsset lvl) 
{ 
    Nodes[,] nodeArray; 
    char[,] matrix = GenerateArray(lvl); 

    nodeArray = new Nodes[matrix.GetLength(0), matrix.GetLength(1)]; 

    for (int row = 0; row < matrix.GetLength(0); row++) 
    { 
     for (int col = 0; col < matrix.GetLength(1); col++) 
     { 
      char type = matrix[row, col]; 
      if (type != '#' && type != '\n') 
      { 
       Debug.LogError(type); 
       Nodes n = new Nodes(row, col, type); 
       nodeArray[row, col] = n; 
       findNeighbors(row, col, matrix, nodeArray); //assuming nodes and matrix variables are instance variables 
      } 
      else 
       nodeArray[row, col] = null; 
     } 
    } 
    return nodeArray; 
} 
public void findNeighbors(int row, int col, char[,] matrix, Nodes[,] nodeArray) 
{ 
    for (int r = -1; r <= 1; r++) 
    { 
     for (int c = -1; c <= 1; c++) 
     { 
      Debug.LogError(row); 
      Debug.LogError(col); 
      if (matrix[row + r, col + c] != '#') 
      { 
       nodeArray[row, col].addEdges(nodeArray[row + r, col + c]); 
      } 
     } 
    } 
} 

GenerateArray()方法工作;我之前使用過。問題來自findNeighbors()。我有這樣的錯誤:

Array Out of range at the row 0 and the columns 19

問題是,我只是有一些#在這裏,它甚至不應該在這裏。我試圖打印該字符,它不打印任何東西,所以我試圖重寫該行,壓制\n等,我什麼也沒有得到。

+2

示例文件的行尾是否爲「\ n」?或者他們是「\ r \ n」? –

+0

我在窗戶上,很好的猜測,那是該死的\ r,謝謝! –

回答

0

據我計算,有18列,你試圖訪問第19列,當然它會拋出這個異常。

你應該放一個,如果像這樣在第二你findneighbors的:

if(row == 0 && r == -1) 
    continue; 
if(col == matrix.GetLength(1) && c == 1) 
    continue; 

也許你可以找到一個更好的辦法做什麼林告訴你,但請記住,如果你不避免訪問不存在的數組的索引,您將不斷收到此錯誤。

編輯。 據我們的同胞們說,有19列,而不是18列,因爲我錯誤地算了一下。我提供的解決方案仍然有效:D

+0

沒有它的19 cols,多數民衆贊成在確定,但由於數組是零索引索引19 ofc超出範圍。這個問題恰好出現在你說的地方。它的邊緣鄰居。最左邊的列沒有col + 1。 – yes