How to get child id or get id by script?

I use factory to spawn a lot of object (20-30) repeatedly , object can delete after hit bullet or move to finish point when game end stop spawn and those object are delete

I don’t want to kept all id in table because is too many id
so I try to keep all in same parent but i don’t know how to get child id or any solution to delete a lot of object

There is no way to iterate game objects that have been childed to a parent game object. But there are many solutions to your problem. First, let’s see if I understand what you are doing, please correct me if I misunderstood anything:

  • You have a game object with a factory component
  • This factory component is used to spawn many objects (20-30)
  • The spawned game objects can be deleted in two ways:
    1. When the object collides with a bullet game object
    1. When something (player?) reaches a finish point then all spawned objects should be deleted

Scenario #1 above could be solved by letting the spawned game object react to collisions with bullets. When this happens the spawned object should simply do a go.delete() to delete itself.

Scenario #2 does actually require you to keep track of all spawned objects in some way so that you can delete all of them. My suggestion is that the game object with the factory keeps track of all spawned game objects in a list and simply iterates this list to delete the game objects. Like this:

function init(self)
	self.spawned_objects = {}
end

local function spawn_object(self)
	local spawned_id = factory.create("#factory")
	table.insert(self.spawned_objects, spawned_id)
end

local function delete_spawned_objects(self)
	for _,spawned_id in pairs(self.spawned_objects) do
		go.delete(spawned_id)
	end
end

In this case you also need to figure out how to deal with spawned objects that was deleted when they hit a bullet in scenario #1 (you don’t want to do go.delete() on something that has already deleted itself). You could let the spawned objects do a msg.post() back to the main script telling the main script that the spawned object has deleted itself and then find it in the list of spawned objects and remove it.

3 Likes

Thank you for your reply and your solution :blush:

1 Like