[SOLVED] Remove Element From Array Without Changing Index

Hello all.
I am making an inventory system and trying to remove items with known indexes (from UI of the inventory window when player drops/uses items) stored in an array. I made an TArray made of FInventoryItem class simply called Inventory. To just test it I tried removing first item from the inventory at index 0 by


    if (Inventory.IsValidIndex(0))
    {

        Inventory.RemoveAt(0, 1, false);
        UpdateInventory(); // This is just updating the UI, it is descrebed below this function
    }

but the thing is it is removing the first item and then shifting the second item in it’s place.
What exactly am I getting wrong here ? I checked around a bit but not sure how to approach this.

Also some tutorials I have seen suggested “making a copy of the array you are working with, working on it and then simply copy it to your real array to prevent crashes and index errors”. Is this a thing ?
Thanks and respects.

RemoveAt is going to shift things down as you remove. If you want to keep indices, you need to replace the value with some default (or a nullptr or whatnot).



Inventory[0] = MyEmptyValue; // This can be a nullptr if you are storing an array of pointers, or you can make some specially defined object that you use as your default.
UpdateInventory(); // Just make sure this code checks for that empty value and skips it.


1 Like

Thanks mate. Using an empty value FInventoryItem worked.

https://i.ibb.co/mTn9PSF/Polkkkkkka.png