简体   繁体   中英

attempt to call method 'insert' (a nil value) when i restart game

I've added objects to the group so they get deleted and respawn when the game restarts but when the game restarts it gives the following error "attempt to call method 'insert' (a nil value)"

This is my object code:

local function spawnObject()
    local objIdx = mRandom(#objects)
    objName = objects[objIdx]

    object = display.newImage( "images/fruit_" .. objName .. "_100.png" )

    object.x = mRandom(screenLeft+30, screenRight-30)
    object.y = screenTop
    object.rotation = mRandom(-15, 15)
    object.id = mRandom(-15,15)

    group:insert( object )

    if objIdx < 4 then
        object.type = "food"
    else
        object.type = "other"
    end

    physics.addBody(object, "dynamic",{radius=45 , bounce = bt})
    grassfront320w:toFront()
    object.collision = objectCollision
    object:addEventListener( "collision", object )
end

And for restarting I go to restart scene which I've created and from there I go back to my play scene.

Please help me solve the problem.

Don't add directly to the group view. Make a separate display group for the objects

local objectGroup = display.newGroup() group:insert(objectGroup)

by doing it this way, you are not obligated to kill out the group when you change scene (if you are using composer or storyboard). It will clear it self in the memory when you change scene.

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