Recently I have been trying to delete all my bodies from Box 2D world and I ran into a little bit of a trouble.
Here is my code for deleting all the bodies:
@Override
public boolean keyDown(int keycode) {
if(keycode==Keys.R){
LevelHolder.clearLevel();
}
}
...
public static void clearLevel(){
System.out.println("deleting bodies");
Array<Body> bodies = new Array<Body>();
world.getBodies(bodies);
for(Body bod: bodies){
world.destroyBody(bod);
}
System.out.println("deleted bodies");
}
And it seems like a reasonable peace of code to me however this crashes sometimes (the message "deleted bodies" never gets printed) with error message from native code:
Assertion failed: (m_bodyCount > 0), function DestroyBody, file /Users/badlogic/jenkins/workspace/libgdx-mac/extensions/gdx-box2d/gdx-box2d/jni/Box2D/Dynamics/b2World.cpp, line 133.
When deleting all bodies that I just got from the world Im somehow deleting more bodies than there are in the world. Also it doesn't happen all the time.
The piece of code is completely isolated and my game has no multi threading. So nothing could be deleting bodies while I'm stepping through all the bodies in the world.
What could be happening here? Maybe this is not the right way of deleting all the bodies and someone could give me an insight of how to do it better? Thank you.
Using libGDX 1.5.2 here.
Try to get the count of bodies first, and then write a for loop that goes through the array using that count, rather than an enumerator. Editing a collection while it's being enumerated can cause issues.