Nested "for each instance" loops produce unexpected results

I’ve ran into what seems like an engine bug, unless I misunderstood something obvious here.

A short explanation of what I’m doing: I have a set of sprites being spawned in the world at random positions. For each of those sprites I then check its neighbors to determine if to spawn corners or edges in empty spaces. To achieve this I use two nested loops through the object group containing the tiles being checked, the first is the tile doing the checking and the second is each potential neighbor. The X and Y positions of each are noted as variables meant to be compared at the end.

The problem is that a test print reveals the loop isn’t working as expected. Normally for the X position of each tile, I should get the X position of each other tile. Instead I only seem to get identical pairs of X positions repeated just once in my test.

What is going wrong here? How do I fix it or what’s the best alternative you suggest? I’m looking for the cheapest option possible so the generator doesn’t get too slow either.

The for each runs for each currently picked instance of an object. Since on each iteration of the for each loop only one object is picked, the second one always iterates on an objects list with a single object in it. Add a “pick all objects” action just before the second loop to make it run on every instances of the object too.

1 Like

That explains it, thanks! I thought it could be something like that: What confused me was the assumption that each time the first loop iterates it resets the picked value thus whenever the second loop starts it will always find the list reset. While this may be true, the first loop indeed turns the list into one value, so the second loop only iterates once like in my observation.

Thankfully I found a way that no longer requires two loops which is better for performance: I pick the neighbors from the conditional entirely, and indeed I do a required “Pick all * objects” per condition for it to work. Fortunately using pick all won’t interfere with the loop it’s used inside of even if the loop iterates over the same object group, so all is good.