我使用Jagged游戏对象数组生成平铺地图,我不断收到错误:
IndexOutOfRangeException:数组索引超出范围。 (wrapper stelemref)对象:stelemref(object,intptr,object) Map.GenerateMap()(在Assets / Scripts / Map.cs:148) Map.Start()(在Assets / Scripts / Map.cs:74)
我完全不知道为什么我会收到此错误。下面是我用锯齿状数组初始化编写的完整函数。据我所知,我正在正确初始化数组。
void GenerateMap(){
mapWidth = Random.Range (5, 25);
mapHeight = Random.Range (5, 25);
//Initialise the Jagged Array
genMapArray = new GameObject [mapHeight][];
for (int i = 0; i < mapHeight; i++)
genMapArray [i] = new GameObject [mapWidth];
//Generate some mountains
int mountX = Random.Range(1, mapWidth - 1); // Random within
int mountY = Random.Range(1, mapHeight - 1); // the map border
for (int y = 0; y < mapHeight+1; y++) {
for (int x = 0; x < mapWidth+1; x++) {
if((y == 0 && x <= mapWidth) || (y <= mapHeight & x == 0) ||
(y== mapHeight && x <= mapWidth) || (y <= mapHeight && x == mapWidth)){
genMapArray[y][x] = Tiles[0];
}else{
if(y == mountY && x == mountX){
genMapArray[y][x] = Tiles[3];
}else{
genMapArray[y][x] = Tiles[1];
}
}
}
}
//Draw Tiles on the Screen
for (int y = 0; y < mapHeight+1; y++) {
for (int x = 0; x < mapWidth+1; x++) {
if (useSquareTiles == true && useHexagonTiles == false) {
GameObject.Instantiate (genMapArray[y][x], new Vector3 (x, mapHeight - y, 0),
Quaternion.Euler (-90, 0, 0));
}
if (useHexagonTiles == true && useSquareTiles == false) {
float hexWidth = 0.75f / Mathf.Cos (Mathf.Deg2Rad * 30.0f);
GameObject.Instantiate (genMapArray[y][x], new Vector3 (x * hexWidth, y + (0.5f * Mathf.Abs (x) % 1), 0),
Quaternion.Euler (-90, 0, 0));
}
}
}
}