I have a problem with objects that have their endObject method called persisting in the scene even after the next frame is called.
The game is a basic shooter where at the end of every game I need to delete all the projectiles and targets from the scene and repopulate it with new targets:
if 'restartGame' in data:
# get current scene
scene=bge.logic.getCurrentScene()
# clean scene from expirable objects
iter = 0
not_clean = True
while not_clean:
# gather expirable objects
balls = [object for object in scene.objects if 'Ball' in object.name]
bullets = [object for object in scene.objects if object.name=='Bullet']
# mark as expired
for ball in balls:
ball.endObject()
for bullet in bullets:
bullet.endObject()
# wait for garbage collection
bge.logic.NextFrame()
# update scene
scene=bge.logic.getCurrentScene()
# check if expirables are gone
balls = [object for object in scene.objects if 'Ball' in object.name]
bullets = [object for object in scene.objects if object.name=='Bullet']
not_clean = (len(balls)+len(bullets)>0)
print('attempt {}: Balls = {}, bullets = {}'.format(iter, len(balls), len(bullets)))
iter += 1
# repopulate targets
scene.addObject('Ball1')
scene.addObject('Ball2')
scene.addObject('Ball3')
Most of the time, the above code works with a single pass of the while loop. Sometimes I get a single bullet persisting. Much more rarely it seems to be impossible to delete any of the objects and I end up with, e.g., 52 bullets and 3 targets in the scene that cannot be deleted. They are not visible, but they remain in the scene and if I break the loop they accumulate.
The weird thing is that sometimes they get deleted by themselves by the time the next call to the restartGame is made. Any ideas for what might be going wrong?
The game is controlled by an outside script through socketing, which makes simply reloading the blend file hard. Any workarounds?