"Rule of Thumb" for when to use For Each loop?

I’m at the point in my game where I’m starting to code a lot of the enemies. It’s a top-down adventure game, and many of the enemies I have planned will use object timers/forces to control their movement (whether randomized or on a set path) with some using Pathfinding.

A lot of the enemies which I’ve added using object timers/forces to control their movement cycles work as intended. However, when I try to add more complex movement to their cycles, it seems to only work properly when I use a For Each object loop (when there are a few of the same enemy on screen at the same time).

Do you have a “rule of thumb” for when a For Each should be used to control something like the movement/actions of multiple enemy objects on screen at the same time? I thought that if you want each instance of the enemy to be taken individually, that is when you need to use a for each. Otherwise, when an action is triggered for one of them (with a Trigger Once), it will sometimes happen to all the other instances as well.

Am I thinking about this correctly? I want to make sure I’m not using For Each loops when I don’t actually need to be using them so that the game runs as smoothly as possible. So what is your “rule of thumb” as to when a For Each Instance event is necessary regarding multiple instances of an object being on screen and active at the same time? Thanks in advance!

1 Like

Trough my all years i never understood it
And by now i don’t care

Only thing that is important to me is that
IF something does not work without it
Then it needs it

And i never needed to understand anything more about it since

That’s about where I’m at right now. I try something without it, and if it isn’t getting the result I want, I figure I must need a For Each to take each instance individually. I figured someone here should be able to explain this in a way that makes sense to a noob like myself.

General rule of thumb is listed here on the wiki: For each object event - GDevelop documentation

There are specific circumstances that do require using a “For Each” event, including:

  • Collisions that need to be handled individually, even if they happen at the same time (such as keeping score or picking up resources)
  • Actions that use an object property or variable that is different for each instance
  • When using linked objects