- Home /
2-Dimensional Array Error [CLOSED]
Im having an issue with my code. It is giving me an error called IndexOutOfRangeException: Array index is out of range. Im not quite sure what Im doing wrong. The code is for a horror game with randomly generated levels...
Here is the code:
using System.Collections;
public class ProceduralGenerationScript : MonoBehaviour {
public int worldX = 12;
public int worldZ = 12;
int[,] roomType;
public GameObject room;
// Use this for initialization
void Start () {
roomType = new int[worldX,worldZ];
for(int i = 0; i <= worldX; i++)
{
for(int j = 0; j <= worldZ; j++)
{
roomType[i, j] = 1;
}
//These Lines Seem To Error...
if(roomType[i, j] == 1)
{
Instantiate(room, new Vector3((float)i, 0, (float)j), Quaternion.identity);
}
}
}
}
}
The array roomType is used to index a certain room and decides what type of room it should be. Just now, it is set up to be that if roomType[i,j] is equal to 1, it will instanciate a roomplace holder(a plane). it works like this:
Instantiate(room, new Vector3((float)i, 0, (float)j), Quaternion.identity);
But not like this:
if(roomType[i, j] == 1)
{
Instantiate(room, new Vector3((float)i, 0, (float)j), Quaternion.identity);
}
Any help is appreciated! :-)
Answer by EvilTak · Aug 24, 2014 at 04:50 PM
In your for loops, you have given i <= worldX
and j <= worldZ
as the condition whereas it should be i < worldX
and j < worldZ
. When you instantiated your array, you mentioned the size as worldX and worldZ. Thus the last element would be worldX-1 and worldZ-1 since arrays start with index 0.
Ok, yep, I understand what I was doing wrong now! thank you. Also, extra points for the quick answer! Thank you.
I ended up going into negative numbers when the array starts at 0. Thank you.
If you thought the answer was appropriate and right, please mark it as correct.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to make a for loop for a class in C# 1 Answer
C# yield error 3 Answers
UNITY_MVP_MATRIX error when downloading A* Pathfinding 1 Answer