Object = nil?

Hi all,

I am trying to make it so that on touch, my object is spawned, then on the 2nd touch an event is triggered with that object.

Right now I have it working so that on the first touch the object is spawned, however on the second touch it seems like the game is unable to find the object I just spawned, and is sending out errors of the object = nil.

Here is my code:

-- spawn object function spawnObject() local object = display.newRect( 0, 0, 50, 50 ) object:setFillColor( 25/255, 25/255, 25/255 ) object.x = 185 object.y = 220 end local function onTouch( event ) if ( event.phase == "began" ) then -- SECOND TAP if startNum == 1 then object:setLinearVelocity( 500, 100 ) end -- FIRST TAP if startNum == 0 then spawnObject() end return true end Runtime:addEventListener( "touch", onTouch )

Thanks!

Looks like a scope issue.  “object” is local to the spawnObject() and isn’t seen outside of it with the code you’ve written. Try:

local object -- spawn object function spawnObject() object = display.newRect( 0, 0, 50, 50 ) object:setFillColor( 25/255, 25/255, 25/255 ) object.x = 185 object.y = 220 end local function onTouch( event ) if ( event.phase == "began" ) then -- SECOND TAP if startNum == 1 then object:setLinearVelocity( 500, 100 ) end -- FIRST TAP if startNum == 0 then spawnObject() end return true end Runtime:addEventListener( "touch", onTouch )

Thank you so much! I really appreciate all the help you’ve given me today (and in the past) :smiley:

Looks like a scope issue.  “object” is local to the spawnObject() and isn’t seen outside of it with the code you’ve written. Try:

local object -- spawn object function spawnObject() object = display.newRect( 0, 0, 50, 50 ) object:setFillColor( 25/255, 25/255, 25/255 ) object.x = 185 object.y = 220 end local function onTouch( event ) if ( event.phase == "began" ) then -- SECOND TAP if startNum == 1 then object:setLinearVelocity( 500, 100 ) end -- FIRST TAP if startNum == 0 then spawnObject() end return true end Runtime:addEventListener( "touch", onTouch )

Thank you so much! I really appreciate all the help you’ve given me today (and in the past) :smiley: