I’ve got a problem. I add some objects from a layer to my scene. Later I need to delete them with “endObject()”. The problem is that only one object ends no metter how often I use the endObject() command.
For example:
for i in range (0,3):
Cube = scene.addObject("Cube",owner)
for i in range (0,3):
Cube = scene.objects["Cube"]
Cube.endObject()
Can anybody explane to me how I can delete objects that have the same name?
You should use that command on the objects! Maybe send message with python(don’t set target, leave blank) with subject “deleteCube” and for the cube you spawn set the logic like so:
Message[“subject == deleteCube”] ---------> And ---------> Edit Object[“End Object”]
This way each of spawned cubes should disappear!
You cannot have more than one object in your scene with the same name.
If you have an object called Cube on an inactive layer, and you add it multiple times to your active layer, you will get objects called “Cube”, “Cube.000”, “Cube.001”, and so on. The reason only one object ends is because there’s only one object called strictly “Cube”.
What you can do, is look for the string in the object’s name:
for object in scene.objects:
if "Cube" in object.name:
object.endObject()
you could have message sent (using the message actuator) out when you want the objects to be removed. on the objects you would have a message sensor looking out for the specific call and it would run the end object actuator. is that what you are looking to do?
I have some python examples though a trivial thing to add, just in case you wanted to delete things one by one
without using loop, the code below will automatically start to delete from the ‘oldest’ living spawn
if sensor.positive:
scene.objects["insert_name"].endObject()
now to do it backward and delete from the ‘youngest’ with loop
for x in scene.objects:
if "insert_name" in x.name:
to_be_removed.append(x)
for y in range(len(to_be_removed)):
num = y
#pass
if sensors.positive:
to_be_removed[num].endObject()
#to_be_removed[y].endObject()# alternative if you pass the loop
Be wary that if you have a large array of spawned objects like 10000 etc, deleting them one by one, especially with the loop method, will spike the logic through the roof