There's a strange glitch that pops up when trying to delete every sprite in a group. I have a group called squaresNoCollide, which contains 68 sprites. I want to delete all of the sprites in this group at once, which the function below is supposed to do:

function clearAll() {
  for (var i = 0; i < squaresNoCollide.length; i++) {
    var sprite = squaresNoCollide.get(i);
    sprite.destroy();
  }
}

But instead it deletes only 34 of the sprites. If I run the loop twice it just deletes half of the sprites again, so the first time it deletes 34, then 16, and so on.
Any ideas on how to fix this? Or, if there's a way to delete every sprite in a group without using a loop at all, that would be helpful too.

    You can use destroyEach() to destroy everything in a group.

    Binary_Coder
    so you're starting from 0 and going up, while the length of the list is getting smaller cuz you're deleting sprites, so you're skipping sprites
    fix this by starting at the length-1 and going while i > -1 and subtracting from i instead of adding to it

    also don't listen to @JMW don't ever become reliant on dum cdo functions

    function clearAll() {
    for (var i = squaresNoCollide.length-1; i > -1; i--) {
    var sprite = squaresNoCollide.get(i);
    sprite.destroy();
    }
    }

      ackvonhuelio most cdo functions probably will use native code instead of interpreted code actually making it 1000x faster...

      ackvonhuelio Oh I get it now, the loop reevaluates squaresNoCollide.length each time. So the problem was just that I’ve been using for loops wrong my entire life. Thanks for your help.

      Chat