ForeEachLoop Crashing the game :( I don't understand why

I have a grid of tiles and an array of them that is made using the “get all of class” node. BEcause of this, the array is random. I’m trying to sort the array by name (into a new array that is) but i’m getting a callstack crash from this fore each loop that i don’t really know the answer for. can someone tellme why i’m getting this error?

this is the second path in a branch in a “for each” loop. the first is for when the sort number is = to 0 (the first tile spawns as just “FloorTile” without the zero)

You are removing objects from the array while you are iterating it with ForEach. I’m pretty sure that is the source of your crash. Manipulating the array in certain ways while going through it will invalidate the iterator and can cause a crash. Instead what you can do is have another empty array called “ToBeRemoved” and add your tiles that you have already carried over instead of removing them from TemporaryTiles outright. Then you can remove all the elements of ToBeRemoved from TemporaryTiles after your ForEach is finished, before you increase SortNumber.

Hope that helps.

Thank you :slight_smile: it’s almost working perfectly now. the only problem is that it stops at tile 32 and doesn’t continue with the other 59

I think it’s because you’re completely clearing TemporaryTiles after the first iteration. You could do it like this:

thanks x2 lol i’d be beeting my head against my laptop if it wasn’t for you :smiley: