Cycling through a List - Dealing with Blank Item issue

Hi all,

Have an interesting issue that I cant seem to solve properly and was hoping someone may have an idea on how to resolve it.

I have a series of Equipment Slots, lets say 4 for this example. I also have a List of owned items. On each slot I made a forward button to cycle through the items in the List. The idea is that with each click of the forward button it will take the first item of the List, add it into the slot, remove that item from the list, then take the current item and drop it into the list. This allows a Cycle through items effect that i am aiming for.

When a player starts out they are going to have empty slots (ID 0) so it will end up adding that Empty item into the list, this is good because then the player can cycle back around to an Empty slot to basically Unequipped any item in that slot. The issue however is when I have 4 slots, it ends up adding 4 empty objects into that list and you can imagine what it would be like to cycle through 4 empty items before getting to the next real item.

I would like to keep 1 empty item in the list for sure but get rid of any extra empty items. I’ve tried various ways to avoid the 0 item but it ends up keeping it at the front of the list so the player can never get to the next item. Below is my CycleItem function in case code can explain what I am doing better then my own explanation :slight_smile:

public void CycleItems()
{
if (statData.owneditems.Count > 0)
{
statData.owneditems.Add(equipitem);
ID = statData.owneditems[0].ID;
OwnedItem newitem = statData.owneditems[0];
statData.owneditems.Remove(newitem);
}
}

Any advise would be appreciated!

why not cycle through your list?
as in:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CycleList : MonoBehaviour {

    Item currentItem;
    List<Item> items = new List<Item>();
    int index;

    //for UI button OnClick
    public void IndexUp()
    {
        index++;
        CycleThroughList();
    }
    public void IndexDown()
    {
        index--;
        CycleThroughList();
    }
    public void CycleThroughList()
    {
        index = index < 0 ? items.Count-1 : index >= items.Count ? 0 : index;
        currentItem = items[index];
    }
}

Just throw in a null check. That way if there isn’t an item in a slot, it doesn’t get added. Then manually add an empty item at the beginning or end.

(Also I don’t fully understand the two list situation, @jister 's way probably makes more sense.)

Thanks @jister

I guess I was over thinking it, as usual. Built upon it to add the current item to the list if it doesn’t equal 0 and also to remove the item from the list if it doesn’t equal 0 and it seems to work perfectly