[SOLVED] Nested loops (repeat for each...), instance traversal

There is a situation in which it is necessary to compare the value of instances of objects with each other. It is logical to make a loop for this object instance, and then make a nested loop again for this object, and compare the values/parameters/variables of the instance of the current loop with the instances of the nested loop.


If we do this, then if there are 4 instances of the Block object on the scene, then we will get the value 4 at the output. Although we should have gotten 16, because it is necessary for each instance to compare it with all instances. But, in this case, an instance is passed to the nested loop instead of an object, as I believe, and the loop executes once, receiving the same value as above.
There are different ways to solve this:

  1. Use an array to store intermediate data for verification.

  2. Use another loop to iterate over the values (more variables are used and “more complex code”)

  3. Use JavaScript, in which nested loops can be done without problems.

I wanted to ask:

  1. Are there more optimal ways (through a list of events) to solve this problem?
  2. Maybe it’s worth expanding the capabilities of the Repeat for each block (or adding a function) so that you can go through all instances of the object anywhere?
1 Like

If you don’t want the instance filtering, maybe wrap your for each with the Repeat N times event with SceneInstancesCount(Block)?
Expressions don’t pick instances, I believe.

But in your situation, it might be better to apply a custom behavior to your objects?

1 Like

Yes, you’re right. If you use Repeat N times as an internal loop, then you can bypass all instances in this way. Thanks. =)

If you mean my example with two Repeat for each, then it is not possible to bypass all instances with an internal loop. And the Collision expression, after successful execution, also outputs only those instances that participated in the contact (if you then output them Repeat for each, in a nested condition). Or I didn’t understand your assumption.

This is rather a general question, I helped a person solve the problem of sorting through neighboring elements: there is a ship consisting of blocks. A block is a sprite with different animations. And as a tile map, a ship is “drawn”. It was necessary to go around and understand which blocks have no neighbors and which have. I wondered, came up with my own solutions, and decided to ask to expand my knowledge about the game engine.

These are expressions:
https://wiki.gdevelop.io/gdevelop5/all-features/expressions-reference

If you use the condition “variable dead of Enemy = 1”, it filters the instances of Enemy matching the condition.
If you do the same, but with the condition ‘compare two values’, no instances are filtered, IIRC.

1 Like

Did you try use the Pick all … objects?