why won't this for each loop work?

I have a simple trigger box in my level to trigger respawn of dead enemies. when they die I add them to an array, and when player character overlaps with this trigger box, they should respawn, using this code:

however, only two enemies respawn (there are 3 enemies, and 3 correct entries in the respawn list array).

If I remove this branch that checks their tags, all 3 will respawn (but i need the tags as i don’t want all dead enemies to respawn) and if I remove the “remove index” node in the end, it will work as well, (except it won’t clear the list).

If I add a branch checking if the array length is not equal to 0, connecting back to the for each loop in case it returns true, then it works. but why wouldn’t the for each loop run as many times as there are entries in that array in first place?

what’s going on? it was working until a few hours ago.

Foreach loop in BP apparently loops through the array using a reference and does not copy it. When you remove an element from an array it automatically shifts all elements after that to left so that indexes still start from 0 to the number of elements - 1.

What this means is, Foreach runs the first iteration and spawns the first actor, then removes the actor from the array shifting every remaining entry 1 index to the left, which makes the original second entry in your array first entry now and the second origin entry the second current entry. On the second iteration your second entry of the array will be spawned (Originally the third actor) and then removed which leaves foreach with no more entries to iterate over (index 0 was already used even though the actor at index 0 at the time was a different actor). This ends the foreach loop with 1 element left in the array and not spawned.
What you can do to solve the problem is to make a new array containing removed indexes, after you spawned all tagged actors loop over it and remove indexes stored from the actors array, then empty the second array (so you won’t unintentionally remove actors next time you use it)

2 Likes

slightly simpler there is no need there to remove the index just clear the array on completed

Judging from the BP he does not want to remove actors that were not respawned which means clearing the whole array is not an option f>.<;

1 Like

ah correct, i missed that

1 Like

Thank you for the explanation! I tried your suggestion and it worked, so thanks a lot

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.