1

嗨,由于某种原因,电晕给了我这个错误:尝试索引全局“backC”(一个零值)

local randomBackC = function()
    backC = display.newImage("Cloud"..tostring(math.random(1, 4))..".png")
    backC.x = math.random (30, 450); backC.y = -20
    physics.addBody( backC, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )
end
timer.performWithDelay( 500, randomBackC, 0 )
end
local function cleanup()
   if backC.y >100 then
       backC:removeSelf()
     end
end
Runtime:addEventListener("enterFrame", cleanup)

关于是什么原因的任何想法?

4

1 回答 1

3

由于Runtime:addEventListener("enterFrame", cleanup)可能已经删除了backC

enterFrame将一遍又一遍地调用 cleanup(),因此您必须在删除backC后删除enterFrame,如果要创建多个对象,请将其仅设置为函数本地,因为它可能会导致引用问题。

像这样

local randomBackC = function()
    local backC = display.newImage("Cloud"..tostring(math.random(1, 4))..".png")
    backC.x = math.random (30, 450); backC.y = -20
    physics.addBody( backC, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )

    local cleanup
    cleanup = function()
       if backC then
           if backC.y >100 then
               backC:removeSelf()
               backC = nil
               Runtime:removeEventListener("enterFrame", cleanup)
           end
       end
    end
    Runtime:addEventListener("enterFrame", cleanup)
end
timer.performWithDelay( 500, randomBackC, 0 )
于 2013-07-05T17:34:42.030 回答