I have an empty GameObject list, and when I try to add items to it using Insert(), i get an error saying: ArgumentOutOfRangeException: Argument is out of range. Parameter name: index
public class Box : MonoBehaviour {
protected List<GameObject> Items;
void Start () {
weapons = new List<GameObject>();
}
public void addItem(GameObject item){
ItemBase item_base = item.GetComponent<ItemBase>();
items.Insert(item_base.item_id, item);
}
}
}
the item_base.item_id is an int. What am I doing wrong?
When using List(t).Insert(int index, T item), the first argument is supposed to be an index to insert the element at, but it has to fit within the current size of the list. The value you use must be greater or equal to 0 AND less or equal to List.Count.
Therefore your item ids may not fit this requirement.
You can use List.Add, then the new element will always end up at the end of the list and it will resize appropriately.
If that is for some reason not suitable, you may need to give more details of what do you want to achieve.