Index was out of range. error
I'm trying making an inventory system, and i want to move items, and swap them with mouse dragging, but for some reason when i move an item to an empty slot it gives the error.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Here is the DropHandler
public void OnDrop(PointerEventData eventData)
{
Item dropped_item = Inventory.instance.items[eventData.pointerDrag.GetComponent<ItemDragHandler>().transform.parent.GetSiblingIndex()];
if (eventData.pointerDrag.transform.parent.name == gameObject.name)
{
return;
}
if (Inventory.instance.items[transform.GetSiblingIndex()] == null)
{
Inventory.instance.items[transform.GetSiblingIndex()] = dropped_item;
Inventory.instance.items[eventData.pointerDrag.GetComponent<ItemDragHandler>().transform.parent.GetSiblingIndex()] = null;
inventoryUI.UpdateUI();
}
}
And here is the DragHandler
private Transform _transform;
private bool is_dragging = false;
public void OnPointerDown(PointerEventData eventData)
{
if (Inventory.instance.items != null)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
is_dragging = true;
_transform = transform.parent;
transform.SetParent(transform.parent.parent);
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
}
}
public void OnDrag(PointerEventData eventData)
{
if (Inventory.instance.items[transform.parent.GetSiblingIndex()] != null && eventData.button == PointerEventData.InputButton.Left)
{
transform.position = Input.mousePosition;
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
is_dragging = false;
transform.SetParent(_transform);
transform.localPosition = Vector3.zero;
GetComponent<CanvasGroup>().blocksRaycasts = true;
}
}
Answer by tormentoarmagedoom · Jan 17, 2019 at 04:12 PM
Good day.
Degub your code while running, the error says what is happening.
Somewhere you are using a index counter (like an array index or list index [i]) And the error occurs when this "i" is higheer o lower than expected.
If you create an array of 3 elements
int[] something = new int[3];
Then you do this:
something[5] = ......
or
..... = something[-1];
The error will occur, because "ArgumentOutOfRangeException: Index was out of range."
So explore your code, debug it while runnning, and try to find where you are trying to access a intex that does not exist, or is still null
(take note that in our example of 3 elements, something[3] does not exist! Only exist 0, 1 and 2 ... Three elements!
Bye