简体   繁体   中英

Why does group:insert fail after a storyboard scene change?

The code sample below is from a single storyboard scene. A magnifying glass (mg), a green circle (asset1), a return button and an animated ship (ship) are all added to the scene's display group as it unfolds. During this, the ship is also removed again with display.remove(ship). This all works fine the first time the scene is created, however, when I click the return button, make a scene change, and then return to this scene, the code fails when it attempts to add the ship to the display group: "attempt to call method 'insert' (a nil value)"

What gives?

    local storyboard = require ("storyboard")
    local widget = require ("widget")
    local scene = storyboard.newScene()
    storyboard.purgeOnSceneChange = true

    function scene:createScene(event)
        local group=self.view
        local asset1x = 600
        local asset1y = 400

    -- MAGNIFYING GLASS
        local mg=display.newImage( "images/mg.jpg" )
        mg.x=600
        mg.y=150
        mg.myName = "mg"
        physics.addBody(mg,"dynamic", { density = 1.0, friction = 0.3, bounce = 0.2, radius = mgRadius})    
        group:insert(mg)            

    -- ASSET PLANT
        local asset1 = display.newCircle(asset1x,asset1y,30)
        asset1:setFillColor(100,200,300)
        physics.addBody(asset1,"static")
        asset1.myName = "asset1"
        asset1.isSensor = true
        asset1.isVisible = false
        group:insert(mg)

        asset1.collision = function(self,event)
            if (event.phase == "began" and event.other.myName == "mg") then
                print("began")
                ship=display.newSprite( shipSheet, shipSeqData )
                ship:play()
                ship:scale(2,2)
                ship.x=asset1x
                ship.y=asset1y
                ship.myName = "ship"
                group:insert(ship)
            elseif (event.phase == "ended" and event.other.myName == "mg") then
                print("ended")
                display.remove(ship)
            end
        end
        asset1:addEventListener("collision")

    -- RETURN BUTTON
        local function returnWelcome(event)
            storyboard.gotoScene("000","fade", 600)
        end
        local returnButton = widget.newButton
        {
            left=900,
            top=385,
            width=300,
            height=225,
            defaultFile="images/bg000.jpg",
            onRelease=returnWelcome,
        }
        group:insert(returnButton)

    end

    scene:addEventListener( "createScene", scene )

    return scene

事实证明,我不小心将mg显示对象两次添加到显示组中,却从未添加过asset1-这在某种程度上引起了该错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM