Where/How to store ONE MAIN REFERENCE to the player which is used across all scenes

I thought I had a nice game coming along until…

I added the option to go from the game.lua to the main_menu scene and back again.  Now on the second time I replay the game, everything is freaking out as I clearly have multiple references to the player happening.

Here is what I’m currently doing regarding my player:

In my main game.lua:

local player function scene:show(event) player = player\_maker.create(options\_about\_player) -- occasionally get info about the player like -- player.lives -- player.score -- etc etc etc end

Then in my player_maker.lua:

local M = {} local player local lives local movePlayer(event) -- code that moves player around end local function onTouch(event) movePlayer(event) end function M.create(options\_about\_player) player = display.newSprite(sheet, sequences) player.lives = lives physics.addBody(player) -- you get the idea, more player related code in here return player end return M

So my question is, how am I supposed to store just 1 player?  I believe I’ve seen some code where there is a destroy() method which cleans up everything but I’m not really sure how exactly that is supposed to be done.

Can someone please give me the general principles on how I should be creating/storing/accessing one player when I’m switching back and forth between the game scene?

I assume you are using composer library, so instead of creating your player in the “show” scene - move your code to the “create” scene,

in addition, bare in mind that the “show” scene invoked twice when moving to the scene - two phases , one named “will” and one named “did”

good luck

Try inserting the player into the scene group

[lua]

function scene:create( event )

 

    – Assign “self.view” to local variable “sceneGroup” for easy reference

    local sceneGroup = self.view

 

    player = player_maker.create(options_about_player)

    – Insert player into “sceneGroup”

    sceneGroup:insert( player )

end

[/lua]

Remember to destroy the scene group when you are finished so it removes the player or manually remove the player