This little tip is probably mostly for users new to blueprints (and programming) but it has come to my attention that there are at least a few people around that are not aware of this, so here goes…
Lets say you have an array of… stuff… that you want to remove some elements from based on some check. For example it could be an inventory array with some expired item(s) that needs to be removed.
At first, you might have tried doing this with a For Each Loop, a *Branch *to check if the item is expired and finally, a Remove Index (or Remove Item) node.
You might not be aware of this if you are new to programming but the problem with that approach is that every time you remove an element from an array, all elements after the removed index will be moved one position upwards.
Say we have an array of 50 elements, starting from index 0 to index 49 (array indexes start from 0).
Then while we are looping through the array elements, let’s say we want to remove the element at index 35 (let’s call it “element 35”).
The element 35 is going to removed just fine but then the elements that come next will be moved by one index… element in index 36 will now be moved in index 35, element 37 will now become element 36 and so on until we end up with an array of 49 elements (ending at index 48).
But since index 36 has been moved to index 35 (essentially taking its place) it will be skipped from the check! That means every time we remove an element, the next one will be skipped… that’s definitely not good right? it means we can remove at max, only 50% of the elements
So what is the easiest way to solve this?
Well… you could simply replace the element at index 35 with an empty element using the Set Array Elem node instead of removing it but that’s not very “clean”, is it?
How about… instead of looping the array from index 0 to 49, we start from 49 and end up at index 0 instead?
That way, when we remove element 35, we don’t care about the re-ordering of elements 36-49 to 35-48 since we have already gone through those.
A reverse for loop.
You can easily make a Blueprint Macro Library with a reverse for each loop macro.
And of course, ReverseForEachLoopWithBreak
Don’t forget to set the macro Category to:
So you can find them easier.