How to remove objects during runtime

Started by AugTech, January 04, 2013, 09:15:35 PM

Previous topic - Next topic

AugTech

Hi.

I'm trying to remove objects from the world during runtime but keep getting a concurrent thread modification error.
I've searched the forum but it seems no-one else is getting this issue?!

I have extended the Object3D class to add a 'allow remove' flag. Every 30seconds within the onDrawFrame method the code below is called, which checks for the flag and calls theWorld.removeObject(o); In the second iteration of the while loop I get the exception and no items are removed from the world - This causes memory issues after some time as more and more objects are added to the world, with none of the old ones being removed.


Enumeration<Object3D> e = theWorld.getObjects();
int i = 0;
try {
while (e.hasMoreElements()) {
A_Object3D o = (A_Object3D) e.nextElement();
if (o.isRemoved()) {
theWorld.removeObject(o);
o=null;
i++;
}
}
} catch (Exception err) {
Log.w(LOG_TAG, "Failed during object removal: "+err.getMessage() );
}



I'll admit I'm not too surprised to get this error, but don't know how to safely remove objects from the world that are no longer required.
Does anyone have any suggestions - i.e. can this only be done within the renderer onPause() event??

Many thanks.

EgonOlsen

You can't remove elements from a list while iterating over it (unless you call remove() on an Iterator, which you don't have here). Just collect the elements to remove in an additional list and remove them based on this list after your loop.

AugTech

Many thanks for the quick response Egon - I should have realised that!!
All working now, Cheers.