I appear to have a memory leak due to my lack of understanding of how to properly use replaceScene()
.
My game has the following (fairly common) situation:
MainMenuScene
-> user presses “Start” -> replaceScene(GameScene)
.
GameScene
-> user presses “Pause” -> pushScene(PauseMenuScene)
.
PauseMenuScene
-> user presses “Main Menu” -> replaceScene(MainMenuScene)
.
So the GameScene
does not appear to be removed from memory; I have seen the memory increase in Instruments and not seen debug log messages appears in various unload methods:
This is not a bug in Cocos2d-x as those methods are behaving exactly as documented, however what’s the correct way to wipe out all scenes and return to the main menu scene?
When you push a scene, it is pushed into the stack.
That means your PauseMenuScene
is the currently running scene.
Now, when you replace scene to MainMenuScene
then the Director
replaces the currently running scene, which is the PauseMenuScene
, but the MainMenuScene
still remains in the stack.
Something like the diagram (showing stack arrangement) -
PauseMenuScene
MainMenuScene
Then, when you replace to MainMenuScene, something like the under happens -
MainMenuScene - (replaces the PauseMenuScene)
MainMenuScene - (previously present and not removed because they Director removes currently running scene from the stack)
May be that’s why there’s a memory leak.
Yes that’s exactly what happens. What I want to know is, how do I avoid it?
if you popScene()
isn’t there not a running scene anymore, so a replaceScene
can only be called if there is a running scene?
The GameScene
will be running after the pop. I haven’t tried it yet - finished coding for the day, but either I can pop and then replace immediately or pass some message to GameScene
to replace. I’d rather not do the latter as its a bit messy.
yes, poping and replacing is a good option.
Hey that works just fine! Many thanks for your help.
hi @slackmoehrle
Just want a clear idea.
Say as the post say some scenes are there -
Something like -
- GameScene - the main game runs in this scene
- ResultScene - pushed scene
Now, If ResultScene
is the running scene
So, If I replace the running scene with GameScene
then in the stack
the old GameScene
would be there and the new GameScene
will replace the ResultScene
right ?
so, the old GameScene
is not removed from the stack.
That will cause memory leak right… ??
could you correct me if I am wrong. ??