- Home /
IndexOutOfRangeException C#
Hey People,
Im pretty new to programming and ran into a problem while working on a script for a inventory system
IndexOutOfRangeException: Array index is out of range. Inventory.Update () (at Assets/_Scripts/Inventory.cs:57)
can anybody spot the problem in my code please?
using UnityEngine;
using System.Collections;
public class Inventory : CollisionDetection {
public GameObject[] InventoryArray;
public int InventoryX;
public float InventoryIncrease;
public float[] targetPosition = new float[0];
public float[] startPosition = new float[0];
public GameObject inventory;
//GameObject[] prefabArray;
public GameObject prefab = null;
public int amountToSpawn; //ARRAY.LENGTH
static public int amountspawned = 0;
public int x;
public int a = 0;
int xCounter = 0;
int y;
Vector3 newPos;
public int pos;
void Spawner (){
for (int i = 0; i < amountToSpawn; i++) {
newPos = transform.position;
newPos.x = newPos.x + xCounter;
newPos.y = newPos.y - y;
xCounter = xCounter + 1;
if(xCounter == x){
y += 1;
xCounter = 0;
}
(Instantiate (prefab, newPos, transform.rotation)as GameObject).transform.parent = inventory.transform;
amountspawned ++;
}
}
// Update is called once per frame
void Update () {
if (InventoryArray.Length >= amountspawned) {
Spawner ();
}
InventoryArray = GameObject.FindGameObjectsWithTag("ItemInInventory");
for ( int i=0; i < InventoryArray.Length; i++) {
print (InventoryArray [0].transform.position);
InventoryArray[i].transform.localScale = new Vector3 (.7f,.7f,.7f);
InventoryArray[a].transform.position = new Vector3(newPos.x,newPos.y,(inventory.transform.position.z)-.5f);
GameObject.FindGameObjectWithTag("ItemInInventory").transform.parent = inventory.transform;
a++;
inventory.SetActive(false);
inventory.SetActive(true);
}
}
}
Answer by Joyrider · Feb 11, 2015 at 09:49 AM
As the debug info tells you, the error is at line 57, and you have an index that is bigger than the highest value of your array.
My guess is you changed the value of `a` in the editor to a value bigger or equal to InventoryArray.Length
the whole script seems to work just fine, but i keep getting the error. I can actually play further with the error
Your answer
![](https://koobas.hobune.stream/wayback/20220613182952im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problem with Singleton and NullReferenceException? 0 Answers
Simple Looping drag and drop game 1 Answer
Array index is out of range error Edited 1 Answer
FindGameobjectsWithTag -> Array 2 Answers
IndexOutOfRangeException: Array index is out of range. 2 Answers