- Home /
IndexOutOfRangeException: Array index is out of range.
I have a script that has an int array but in unity I get the error "index out of range" and don't know whats wrong with it here's my script
using System.Collections;
using UnityEngine.UI;
using UnityEngine;
public class Inventory : MonoBehaviour {
public Text inventoryText;
int[] counts = new int[8];
void Update () {
inventoryText.text = "Grass:" + counts[0] + "\nDirt:" + counts[1] + "\nStone:" + counts[2] + "\nDrysand:" + counts[3] + "\nWetSand:" + counts[4] + "\nCoal:" + counts[5] + "\nIron:" + counts[6] + "\nGold:" + counts[7] + "\nDiamonds:" + counts[8];
}
public void Add (int tileType, int count){
}
}
the arrays the right size( 8 in length)
Answer by carle13 · Jul 14, 2017 at 07:04 AM
Try deleting the "counts[8]". I think you get the error because when you give the array the length of 8 the array has literally 8 spaces, but when you access the variables inside the array the 8 is out of range because the array starts from 0.
Yes, because the array doesn't have an element [8]. Or you can give it a size of 9 int[] counts = new int[9];
Answer by TWicked · Jul 14, 2017 at 08:07 AM
Your array initialized for 8 integers (0 to 7) but in your text box you are requesting 9 integers (0-8) Your solution would be to change int[] counts = new int[8]; to int[] counts = new int[9];