2015-05-06 33 views
-1

我想從外部數據文件讀取文件,將它們粘貼到數組中以導入到Unity3D。 於是我開始這樣的:將文件中的值讀入多維數組

int [,] positionTab = new int[noLoc,3]; 

StreamReader sr = new StreamReader(myTextFile); 
while((line = sr.ReadLine()) != null)//read line by line up to the end 
{ 
    if (line.Contains("confTrain1")) 
    { 
     locationTrain1 = RetrieveValueInDataFile.locationTrain(line); 
    } 
    else if (line.Contains("confTrain2")) 
    { 
     locationTrain2 = RetrieveValueInDataFile.locationTrain(line); 
    } 
    else 
    { 
     distanceBetweenThem =RetrieveValueInDataFile.distBetweenTrain(line); 
    } 

我不知道有這樣的:

int [,] locations = new int [noLoc, 3] 
{ 
{locationTrain1, locationTrain2, distanceBetweenThem} 
{locationTrain1, locationTrain2, distanceBetweenThem} 
{etc} 
} 

的問題是我不知道如何做到這一點的StreamReader的。我的意思是,我如何添加兩個位置和距離(語法)?

回答

0

構建數組時只能使用這種數組初始化語法。

如果您需要設置一個現有的陣列的值(如您的樣品中) - 使用索引:

int [,] locations = new int [noLoc, 3] 
var rowIndex = 0; 
using(StreamReader sr = new StreamReader(myTextFile)) 
{ 
    while(
     rowIndex < noLoc && // if using array you have to read no more than allocated 
     (line = sr.ReadLine()) != null) 
    { 
     locations[rowIndex,0] = locationTrain1; 
     locations[rowIndex,1] = locationTrain2; 
     locations[rowIndex,2] = distanceBetweenThem; 
     rowIndex++; 
    } 
} 

注意,它可能會更好地定義類,用於保存此值,並將其存儲在一個列表,當你閱讀它們。

+0

好吧,我會試試這個。謝謝。 – AuroreT