Problem spawning multiple sprites

Hi guys!

I’m using Composer and I’m trying to create a function that spawns a ghost animation every 4 seconds. It is currently set to spawn 5 in total. The function works fine, my problem is that the app crashes if the user moves to the next scene before all 5 sprites have appeared. This is my code:

function spawnGhost1()     local sheetInfo = require("ghost1Sprite")     local ghostSheet1 = graphics.newImageSheet( "ghost1Sprite.png", sheetInfo:getSheet() )     local sequenceDataG1 =     {name="floating", start = 1, time = 800, loopCount = 0, count=6}            local ghostSprite1 = display.newSprite(ghostSheet1, sequenceDataG1)     ghostSprite1.x = display.contentWidth\*1.5     ghostSprite1.y = display.contentHeight/5       ghostSprite1:play()     transition.to(ghostSprite1, {x=-display.contentWidth, time=12000})     sceneGroup:insert(ghostSprite1)     ghostSprite1:addEventListener("tap", removeGhost)     return ghostSprite1   end 

I call the function in the show:did function 

timer.performWithDelay(4000, spawnGhost1, 5)

Is there a better approach to generating multiple sprites? I ultimately want to generate a larger number of sprites, allowing the user to be able to interact with this screen for as long as they want but then move on to the next page when they want, as opposed to waiting until all sprites have generated. (it’s a storybook app) How can I prevent this crash?

Hi @amy.laura.b,

In this case, you should assign an upvalue (forward) reference/handle to the timer, and then when the scene is about to exit (“hide” > “will”), cancel the timer by its handle. That will stop the ghosts from spawning, and you won’t get the error in the next scene.

Best regards,

Brent

Hi @amy.laura.b,

In this case, you should assign an upvalue (forward) reference/handle to the timer, and then when the scene is about to exit (“hide” > “will”), cancel the timer by its handle. That will stop the ghosts from spawning, and you won’t get the error in the next scene.

Best regards,

Brent