我正在嘗試在文本平鋪中讀取,並在遊戲運行時使用它來顯示地圖。 當我讀取一個大於0的數字(我認爲)時遇到問題。使用2D數組和文本文件統一創建平鋪地圖
將顯示第一列中的對象,但不會有其他任何東西。我再次認爲它是因爲它是tiles [0]的位置。
這是錯誤我得到:
IndexOutOfRangeException:數組索引超出範圍。 Map.loadMap()(在資產/光子統一網絡/腳本/遊戲地圖/ Map.cs:49)
這裏的地圖文件
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 6 1 1 1 1 1 1 1 1 1 1 1 4 4 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 4 0
0 1 1 1 1 1 1 3 1 1 1 1 1 2 2 0
0 5 1 1 1 1 3 3 3 2 2 7 2 2 1 0
0 1 1 2 7 2 2 3 2 2 1 1 1 1 5 0
0 1 2 2 4 1 1 1 1 1 1 1 1 1 1 0
0 2 2 4 4 1 1 1 1 1 1 1 1 1 6 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
,這裏是我的地圖代碼。
int X, Y;
public int mapHeight;
public int mapWidth;
GameObject mapTile;
GameObject [,] mapArray;
public GameObject [] Tiles = new GameObject[8]; //this is an array of the tile objects
/* UNITY FUNCTIONS */
void Awake(){
}
void Start() {
loadMap();
}
void Update() {
}
/* DATA MANAGEMENT */
void loadMap(){
string input = File.ReadAllText(Application.dataPath +
"/Resources/Maps/map0.txt");
mapHeight = 9;
mapWidth = 15;
mapArray = new GameObject [mapHeight,mapWidth];
int i = 0, j = 0;
foreach (var row in input.Split('\n'))
{
foreach (var col in row.Trim().Split(' '))
{
mapArray[i, j] = Tiles[int.Parse(col.Trim())]; //Get the GameObject from the Tiles
mapTile = mapArray[i, j]; //array and att it to the map array
GameObject.Instantiate(mapTile, new Vector3(i, j, 0),
Quaternion.Euler(0, 0, 0)); //display it on screen
j++;
}
i++;
}
}
任何幫助將不勝感謝你。
使用附加的調試器啓動遊戲(在monodevelop中運行命中),然後您會看到它崩潰的位置以及i和j的值。您還可以設置斷點並逐步查看錯誤。您可能需要添加斷言來測試您的假設,即有9行和15列。 – LearnCocos2D 2014-10-01 18:34:39