Author Topic: How to remove objects during runtime  (Read 788 times)

Offline AugTech

  • int
  • **
  • Posts: 64
    • View Profile
    • Augmented Technologies
How to remove objects during runtime
« on: January 04, 2013, 09:15:35 pm »
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.

Code: [Select]
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.

Offline EgonOlsen

  • Administrator
  • quad
  • *****
  • Posts: 11748
    • View Profile
    • http://www.jpct.net
Re: How to remove objects during runtime
« Reply #1 on: January 04, 2013, 09:19:07 pm »
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.

Offline AugTech

  • int
  • **
  • Posts: 64
    • View Profile
    • Augmented Technologies
Re: How to remove objects during runtime
« Reply #2 on: January 04, 2013, 09:48:14 pm »
Many thanks for the quick response Egon - I should have realised that!!
All working now, Cheers.