Scrolling inventory script giving argument out of range.

So i have a script that controls the scrolling hotbar / inventory. Here is what I have:`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Inventory : MonoBehaviour {

public List<Obj> Inven = new List<Obj>();

public Image slot2;
public Image slot3;
public Image slot4;

public Obj selectedSlot;
public Obj selectedSlottakeone;
public Obj selectedSlotplusone;

public float mouseSelected;

public float selected;

// Use this for initialization
void Start () {
    selected = 1;
   

}

// Update is called once per frame
void Update () {

    if (selected < Inven.Count)
    {
        selected = Inven.Count;
    }

    if (selected < 0)
    {
        selected = 0;
    }
    if (Inven.Count != 0)
    {
        selectedSlot = Inven[(int)selected];
        if (selected - 1 >= 0)
            selectedSlottakeone = Inven[(int)selected - 1];
        if (selected + 1 <= Inven.Count)
        selectedSlotplusone = Inven[(int)selected + 1];
        slot3.sprite = selectedSlot.img;
        slot4.sprite = selectedSlotplusone.img;
        slot2.sprite = selectedSlottakeone.img;
    } 

    selected += Input.GetAxis("Mouse ScrollWheel");
   

}

}
`

I am getting the error argument out of range at line 44.
can anyone help?

it looks like you are calling +1 larger than the List size on that line.

List.Count = the size of the list
so if there are 12 items in the list, List.Count = 12.

when you call List[12 +1] you are taking it out of range.

Hello there,

As previously said, the problem is that you’re assigning selected to your list size (count), and then using it as an index for that same list. That means, if the line selected = Inven.Count is reached, the line selectedSlot = Inven[(int)selected]; will give you an error.

replace selected = Inven.Count with selected = Inven.Count -1 and you should be fine, as selected would then point to the last item in your list.

Hope that helps!

Cheers,

~LegendBacon