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! :slight_smile:

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.