I’ve been working on my first game built on Corona for several months, and I’ve got it in Alpha testing at the Google Play store now. All seems good, except…
A couple testers report an intermittent bug that I’ve seen only once (and can’t duplicate). Unfortunately they see it a little more frequently than I do. The bug happens after a game is completed and the user tries to “play again.” Occasionally, some display objects from the last game aren’t cleared from the display.
I’m using composer, inserting all my display objects into groups and then inserting them into the sceneGrooup. At the end of every game/scene I call composer.removeScene() on scene:hide() intending to remove everything before the next scene. As I say usually his works.
When I went hunting through my code to find what I had missed, I did discover an error where I had set one of my display objects to nil, without first removing it from the display. My first question is…
- Could that mistake have caused composer.removeScene() to get confused when it tried to remove all objects and leave some _other_ objects on the screen? I speculating that if the garbage collector came along and (intermittently) removed the display object before composer tried to remove it that might cause a problem.
So, I fixed that mistake but I thought what if there are other mistakes like that. I admit I have made more than one mistake in my life. So, I started thinking, “Maybe I can explicitly remove all objects from the main stage before I fire up the new scene and that will correct for any other lurking mistakes.” Assuming that’s a good approach, the second question is…
- How can I clear out the display stage before I create a new scene?
I couldn’t find anything like display.currentStage.removeAll() and eventually I tried the code below. It sort of works, in that it doesn’t seem to cause any harm, but I’m hoping someone else has a better idea.
function clearTheStage() local stage = display.currentStage if (stage.numChildren \> 3) then for i=4,stage.numChildren do local child = stage[i] display.remove(child) print( "stageChild["..i.."] was removed " ) end else print ("left the first 3 objects on the stage") end end
Actually, in my first attempt, I tried to clear all the children, starting with stage[1] but that didn’t go so well. I invoked clearTheStage() in the composer scene:ceate() function and then all I got from scene:show() was a blank screen. I’m thinking composer creates some child objects in the display stage that need to be around for it to work, like maybe composer.stage
So, as you can tell I’m experimenting here. Maybe I should re-phrase the second question to, “How can I guarantee that the stage is clear before I create a new scene?”