Delete all objects in a spawned array of objects

From the example: I have taken the lines of:

// Loop through Entities and delete them when their time is up
for (i = 0; i < this.entities.length; i++) {
    this.entities[i].timer -= dt;
    if (this.entities[i].timer < 0) {
        // entity.destroy() deletes all components and removes Entity from the hierarchy

        // Remove from the local list
        this.entities.splice(i, 1);
  • this in order to create a script than runs through all at once to delete all objects.
    These examples fails by only deleting some, alongside halting the system at the end - why?:

for (i = 0; i < this.entities.length; i++) {
try{ this.entities[i].entity.destroy(); } catch(error){console.error(error);} // The actual objects only?
try{ this.entities.splice(i, 1);} catch(error){console.error(error);} // One way that doesn’t give correct result
try{ this.entities.splice(i-1, 1);} catch(error){console.error(error);} // another try (no help either)

Do you have a project link that you can share which showcases the error?

It looks like you are attempting to remove an entry while iterating through the list from 0->end. The common idiom is to reverse iterate (end->0). That way, removing an item doesn’t affect the iteration.

In your current method, if you delete index 3 of an array of size 5. What was index 4, now becomes index 3 but the for loop will be looking at index 4, completely skipping over an entry.

ok, it works with the reverse approach (which I actually use normally in such iterations anyway) - thx
but is there an easier way to empty the array? (I might find a strict javascript way elsewhere but this is 3d objects as well - sense that there is a difference from these vs strings for instance)

(ps: I am not sure that I will share the project -> due to my corp and infringement etc)

What do you envision to be ‘easier’? In your example, there’s timers on each entity so I’m not sure what you are expecting to make this easier? Is there some context I’m missing here?

[as own clean-up] answer #1 actually helped me -> solved