Inventory System - Find Empty Slot

Hey guys,

I’m currently designing an inventory system, but it’s pretty complex stuff.

What I want to do is this:

If player picks up an item, the game should look through the ‘inventory’ gameObject (that has a lot of variables for each slot with states like ‘item’, ‘isEmpty’, etc.), find out if there’s an empty slot left in the inventory and then set the picked up item to that empty slot.

The part where I have problems is in actually finding out through the script which inventory slot is still empty.

Say we have 10 slots, the first 5 are already filled with items, the 6th one is empty. The code should be like:

If item was picked up
→ var freeSlot: Go through all the inventory slots starting at 1 and find the next one that’s empty.
→ if empty found: Set Item that was picked up to freeSlot
→ if no empty found: Item can’t be picked up.

I think I just lack some programming knowledge in how to ask this. I’m pretty sure I could get it to work with a ton of if/else statements, but that’s probably not the smart way to do it. Any hints?

I am not sure if your slots are game Objects or variables but This can be done with a for loop like this. lets say its a string variable array.

NextEmptySlot = FindEmptySlot();

function FindEmptySlot(EmptySlot : String ){

     for (var i = 0; i < Slots; i++;
     {
         if(Slots *== "isEmpty")*

{
return Slots*;*
}
}
return Full;
}
You cant copy and paste my code because I am no where where I could test it but that is the idea. The for Loop function is returning a string, you could also have it return a game object. It then goes thru your Slots array and checks if its string is equal to isEmpty. If so, it will return that Slot arrays index. If it went thru the entire loop and did not return any slot it will return full.
I hope that gets you on the right track.

in my case my code when breaking the tree it quanha item drop chances, but I just managed to create new slot, what I want to do is select a empty slot and add new item

foreach (ItemDropChance itemChance in dropChances)
            if (Random.value <= itemChance.probability)
                player.inventory.Add(new ItemSlot(new Item(itemChance.item)));

,in my case my code when breaking the tree it quanha item drop chances, but I just managed to create new slot, what I want to do is select a empty slot and add new item

foreach (ItemDropChance itemChance in dropChances)
if (Random.value <= itemChance.probability)
player.inventory.Add(new ItemSlot(new Item(itemChance.item)));