How to destroy the widget button when gotoScene is called

Hi,guys,
How to destroy the widget button when gotoScene is called?

local function handlePlayButtonEvent(event)
    if ( "ended" == event.phase ) then -- Debug
        composer.gotoScene( "scene.game",{ effect = "slideDown", params = { } })
    end
end

    local playButton = widget.newButton(
    {
        label = "Play",
        labelColor = { default={ 1, 1, 1 }, over={ 1, 1, 1, 0.55 } },
        fontSize = 32,
        x = display.contentCenterX,
        y = display.contentCenterY + 60,
        -- Properties for a rounded rectangle button
        emboss = true,
        textOnly = true,
        onEvent = handlePlayButtonEvent
    }
)

You may want to look into Composer and Scene Management on documentation. Here: https://docs.coronalabs.com/guide/system/composer/index.html#scene-management

Provide my approach. Using groups can also ensure that you will not make mistakes when deleting “non-existent objects”.

local WidgetGroup = display.newGroup()

local function ClearFunction()
	for i = WidgetGroup.numChildren,1,-1 do
		WidgetGroup[i]:removeSelf()
	end
end

local function handlePlayButtonEvent(event)
    if ( "ended" == event.phase ) then -- Debug
		ClearFunction()
        composer.gotoScene( "scene.game",{ effect = "slideDown", params = { } })
    end
end

    local playButton = widget.newButton(
    {
        label = "Play",
        labelColor = { default={ 1, 1, 1 }, over={ 1, 1, 1, 0.55 } },
        fontSize = 32,
        x = display.contentCenterX,
        y = display.contentCenterY + 60,
        -- Properties for a rounded rectangle button
        emboss = true,
        textOnly = true,
        onEvent = handlePlayButtonEvent
    }
)
WidgetGroup:insert(playButton)

Thank you! :smiley:

Wouldn’t it be easier to simply insert the widget button directly into the sceneGroup? (Or, if you had a reason for wanting the buttons in their own group, inserting the WidgetGroup into the sceneGroup.) That way it would be destroyed automatically when the scene changes without the extra step of manually running a removeSelf.