Preserving list indexes when removing items from a list.

Hi,

Suppose I’m creating an inventory system using a list. suppose the inventory system has 6 slots so there are indexes from 0 - 5. suppose I have slots 1 to 4 filled. If I have a method called UseSlotItem(index); which uses an item from the index of that list and after the item has been used, I use RemoveAt(index) to remove that item from the list. Is there a way to keep the items indexs without making them move?
so If I have 1 to 4 slots filled, I use the 3rd item, item of index 4 becomes item of index 3 is there a way to keep that indexes without making them move around.

A good example would be Minecraft’s inventory system. There are 9 slots, If i have slots 1 to 5 filled and I drop the item in slot 3, then clicking on slot 3 again wouldn’t active what is on slot 4 because the items don’t shift, rather they stay the same place, How can I achieve the same thing using lists or any other collection in Unity?

Use an array.

Though to make a GOOD inventory system would be to do something like so.

public class Slot : System.Object {
    protected Item m_item;
    protected int m_quantity;

    public Slot(Item item) {
        this.m_item = item;
    }

    public void SetItem(Item item) {
        if(this.m_item != null) {
            if(this.m_item.GetType() == item.GetType()) {
                this.m_quantity++;
            } else {
                Debug.Log("Item slot taken!");
            }
        } else {
            this.m_item = item;
        }
    }

    public void Use() {
        if(this.m_item != null) {
            this.m_item.Consume();
        } else {
            Debug.Log("No item in slot!");
        }
    }

    public void Drop() {
        if(this.m_item != null) {
            this.m_quantity--;

            if(this.m_quantity <= 0) {
                this.m_item.Dropped();
                this.m_item = null;
            }
        } else {
            Debug.Log("No Item to drop!");
        }
    }
}

[System.Serializable]
public abstract class Item : System.Object {
    public abstract void Consume();
    public abstract void Dropped();
}

public class Demo : MonoBehaviour {
    // Make an inventory with 3 slots empty.
    [SerializeField] Slot[] m_inventory = new Slot[] {
        new Slot(null),
        new Slot(null),
        new Slot(null)
    };
}

Thanks for that, since I want to keep it simple, do you mind showing me a simpler example using Arrays? say I have 6 slots, how would I go about doing that?

When initializing the array, initialize with 6 slots instead of 3 like I did.

Awesome, let you know how it goes :slight_smile: