Track number of objects on screen

I am working with know the number of an object on the screen and how to trigger an event when they are all gone.

[code]local crates = {}

for i = 1, 5 do
for j = 1, 5 do
crates[i] = display.newImage( “crate.png”, 20 + (i*50), 220 - (j*50) )
physics.addBody( crates[i], { density=0.2, friction=0.1, bounce=0.5 } )
end
end[/code]

what is the best way/how can I trigger an event when all the “crates” have left the screen?
[import]uid: 15043 topic_id: 6760 reply_id: 306760[/import]

Hello, you can remove each “crate” from array when a collision occur and evaluate in “enterFrame” event the size of array. If size == 0 then all “crates” have left the screen.

Regards.
Francisco.
[import]uid: 11749 topic_id: 6760 reply_id: 23604[/import]

You could also add all the crates to one display group - by adding the reference to the display group in front of the filename in the newImage call - and checking the .numChildren property of that group.

eg:
[lua]for i = 1, 5 do
for j = 1, 5 do

– create display group to sit on top of previous display group
– accessed using display.getCurrentStage()[]
local cratelayer = display.newGroup()

– add new crate to current display group ‘layer’
– accessed by retrieving the display group, as above, and indexing that group
local crate = display.newImage( cratelayer, “crate.png”, 20 + (i50), 220 - (j50) )
physics.addBody( crate, { density=0.2, friction=0.1, bounce=0.5 } )

end
end

– to get the 3rd crate from the 4th layer (the one below the top layer) do
local acrate = display.getCurrentStage()[4][3][/lua]

It’s basically the same as what @ffm suggested, except it uses the display system to do the organisation and the inherent benefits thereof.

[EDIT] Also, I just noticed that your posted code always adds the five crates using the i index to the crates table, meaning only the last iteration of the j loop would leave any references to any display objects, while the display objects themselves would still be on the screen. In short: You are losing the first 20 crate display objects from your table because you’re overwriting them in each j loop. My sample above fixes that by adding each j loop’s crates to the group for that iteration. [import]uid: 8271 topic_id: 6760 reply_id: 23612[/import]