- Home /
List Insert() returns Argument is out of range
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?
Answer by VesuvianPrime · Sep 11, 2014 at 10:47 PM
The List collection doesn't let you have spaces, so if I was to do something like:
List<string> myList = new List<string>();
myList.Insert(9, "Derp");
This isn't going to work because the list currently has a size of zero. This also applies to:
List<string> myList = new List<string>();
myList.Insert(0, "Derp");
I think what you're looking for is a dictionary:
Dictionary<int, GameOject> items = new Dictionary<int, GameOject>();
items[item_id] = item;
Actually, you can use Insert with index equal to size of the List, this will work the same as Add (added at the end of list) - $$anonymous$$SDN documentation
Answer by AyAMrau · Sep 11, 2014 at 10:47 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613162827im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
A node in a childnode? 1 Answer
Clear Does not work to remove 1 Answer