[Box2D] Game crashes when I try to destroy bodies.

In my main class:

		/* next step for physics events */
		toDestroy = new Vector<Body>();
		w.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);
		//System.out.println(theBall.getPos()+" | "+Math.abs(Math.toDegrees(theBall.getRotation()))%360);
		
		/* destroy objects for destruction (e.g. - experience gems that have been picked up, bullets that have collided with another object) */
		for (int i=0;i<toDestroy.size();i++){
			Body b = toDestroy.elementAt(i);
			b.setAwake(false);
			w.destroyBody(b);
		}

In my class that contains the physics world, its objects and the collision listener:

	private void createCollisionListener() {
		ContactListener cl = new ContactListener() {


            @Override
            public void beginContact(Contact contact) {
                Fixture fixtureA = contact.getFixtureA();
                Fixture fixtureB = contact.getFixtureB();
                LogapBall lball = cast(fixtureA.getBody().getUserData(), fixtureB.getBody().getUserData(), LogapBall.class);
                LogapExpGem leg = cast(fixtureA.getBody().getUserData(), fixtureB.getBody().getUserData(), LogapExpGem.class);
                LogapBox lbox = cast(fixtureA.getBody().getUserData(), fixtureB.getBody().getUserData(), LogapBox.class);
                LogapBullet lbull = cast(fixtureA.getBody().getUserData(), fixtureB.getBody().getUserData(), LogapBullet.class);

               if(lbull !=null && lball == null){
            	  ItLoGaP.toDestroy.addElement(lbull.getBody());
               }

I read somewhere that a usual cause of the app crashing when trying to destroy box2d objects is when you’re trying to destroy the object inside the world step. This is why I just created a Vector in the main class, which is populated with bodies to destroy while the world step is ongoing so that once the step finishes, that’s the only time when the bodies will actually be destroyed.

So now that my game is still crashing… I have no idea what’s still causing it.

Do you clear the destroy list somewhere ? Do you mess with multiple threads ?
Btw, instead of Vector I would rather recommend to use ArrayList.

Removing object twice will crash box2d so you need to check and remove duplicate body references from toDestroy list before remove loop.

Another option, though I don’t know how it would impact performance in the speed direction, would be to use a HashSet to hold your to destroy list. It abstracts out your need to actually remove duplicates.

Thanks everyone! It looks like it was being caused by the duplicates issue. I implemented it instead using HashSet as UprightPath suggested and it seems to be working now :slight_smile: