[Solved] Issue with For Each Loop

I’m doing some simple enemy IA for a platform game but I’m having some problems with a For Each loop.

I use a For Each llop to iterate trough all the enemies of the scene and then check if they are colliding with a helper object that make them change direction; it’s very simple, but when two or more of the enemies are colliding with a helper object at the same time things stop working properly (enemies don’t change direction and/or get stuck).

I manage to isolate the issue in a sample project you can see and download here:


Any help will be greatly appreciated!

General heads up, “Trigger once” does not work within For Each loops, or at least not how you’d expect (it only triggers once for the first instance, then all other instances are every frame). You’ll probably need a “hasHappened” boolean variable on the objects that you toggle to ensure it only happens once, then reset it via events (likely checking that is no longer in collision with helper_turn).

I would also move your actual movement events outside of the for each loop, as that will fire for all enemy instances without needing to be a “For each”.

Here’s how I set up the patroller logic in Not-A-Vania, and it does what you’re looking for even if I have 100 skeletons in the same spot. I do use separate left/right objects, though. With a single object you’ll need the toggle variable I mentioned instead.

1 Like


That does the trick.