Removing Empty space from Player inventory after adding/removing items

My game requires adding and removing items from the player’s backpack. Currently, I am doing this by parenting the items to the backpack to add and destroying the items to remove. This works fine until, for example, item ‘2’ is destroyed in the following list of items:

1,2,3

which becomes a backpack of 1,3 which can seem jarring to the player rather than the inventory rearranging itself.

I am looking to clear these empty spaces so that after destroying item 2, I can rearrange the backpack to remove the empty space so it becomes a backpack of 1,2. I had a look on the player.Backpack documentation but it didnt mention any methods for clearing empty space or rearranging the positions of the player’s inventory, but it must be held in a list somewhere surely. Thanks for any help.

Use GetChildren() to get the items you need, use table.remove() to get rid of the items, then you could iterate thorugh the rest to re-insert them. Something like:

RemoteEvent.OnServerEvent:Connect(function(player, item)
    local backpack = player.Backpack
    local items = backpack:GetChildren()
    for _, item in ipairs(backpack:GetChildren()) do
        item:Destroy()
    end
    table.remove(items, item) -- 'item' must be the index of the item in the list
    for _, tool in ipairs(items) do
        --re-inserting code here
    end
end)

Make sure to keep a backup of your old code - I haven’t tested this so I’m not sure if it works or not.

1 Like

That does seem to be the answer, just having trouble implementing it myself but I’ll let you know if I’m stuck.

1 Like

Better create your own Backpack. Otherwise, you will not be able to interact with internal elements in any way; the only way is to set parent to nil for the rest when removing an item from your inventory and return them to the backpack.

By this do you mean a list that is a child of the player, storing tool instances and using table.find(list,object) instead and disabling the standard backpack and instead using a custom inventory system? (custom gui, equipping system)

Yes, you are right. You will simply disable the Backpack UI, but the Backpack itself will remain, so table.find is not necessary.