How can I properly destroy actors from an array inside a loop

Hi there

I have some behavior that I find is a little weird. I have a collider wich represents an explosion. The first tick that the collider is active I use GetOverlappingActors to get any targets hit. I then use a for each loop, to iterate over the targets and deal damage .My problem is that if a target dies (and is destroyed) the array is changed (the destroyed element removed), but the iterator is the same. Which means that if all targets should be destroyed, effectively only half of them are affected.

Personally I think this is a really dangerous design. But right now I’m just looking a for a proper solution. I can see several fixes, but I don’t like any of them for various reasons.

  1. Add a delay before destroying the actor. While this will probably work in most cases, I don’t like it conceptually as I feel it could introduce race conditions.

  2. Instead of destroying actors right away, mark them for destrouction and destroy them on the next tick. This might work, depending on how the engine executes tick events (if it is sequential execution). But I feel it adds unnecessary complexity.

Any suggestions? Either a loop solution that avoids the problem, or a better workaround.

This is indeed a frustrating limitation. Why is there no backwards loop? Or a way to invert an array?

Delays and MarkForDestruction work fine for handling delayed destruction of the object itself but I think it could be confusing if the actor than refers back to the array (which is presumably held elsewhere) to remove itself. Hmm… you probably mean a delay calling Remove on the array. Still seems confusing.

Other suggestions:

Good luck!

Hmm… Not the answer I was hoping for. :stuck_out_tongue:

I think a reversed for-loop is actually the best workaround solution. But why on earth doesn’t the for-loop node support reverse order, like almost all programming languages.

Ah well, I’ll make something myself. Thanks for the input!

get the length of the array and another variable, add to that variable every time an object is destroyed and minus the length and the variable to get the end of the loop

Had the same issue and solved it by running a reverse while loop. Thanks for the hint!

Here how i doing it: