mutating array and item indexes

a wee while ago, I had to deal with mutating array (as I learned what it was called). Basically as my game refer to array indexes in actors, when I remove items from the array the indexes are all out of whack because I delete or add items to the array.

The work around what that I keep references (double linked) and every time I remove an item from the array I make sure to update my references.

But as time goes on I realise how prevenlant this issue is, I constantly delete stuff from arrays and it feels really bad to refreshing the indexes to maintain the links (particularly between levels when I load everything back into game instance.

A simple example where I’m facing this again.

I link my item in inventory to an array index (because widgets aren’t persisted between level loads) I don’t load too much into the widget. however, as soon as I delete 1 item from the array all my inventory item id’s are broken…

I seem to be missing a developer pattern here, can anyone please share how they optimized this ?

Thank you!

So I just googled a wee bit…

I figured this will work well with minimal code changes.
When I delete items (which cause the mutation) I will item the item to a list (another list of deleted items) and I will “soft” delete the item from the array.

I will then use this list and before I add items just by .add I will check the delete list to see if there are indexes and I can just insert (and overwrite) at the index. and then delete the item from the deleted list.

Should work good enough .

1 Like