I’ve got a simple set of buttons in a game that are disabled at a certain point, then re-enabled when a fresh round starts.
For some reason when I removeEventListener (so the button can’t be clicked) then addEventListener back again however, when the buttons are clicked they run their respective functions twice.
On the first click (before removeEventListener), the button function runs just once as expected, and the same goes if I never try to remove then re-add the event listener.
Am I missing something obvious here? The code below was just a quick test I smacked together to see if I was crazy, but it exibits the same behavior as my game in progress; running the button functions twice after being turn off then back on.
[lua]-- Make a rectangle to act as one button.
myButton = display.newRect(80, 200, 150, 50)
myButton.strokeWidth = 3
myButton:setFillColor(140, 140, 140)
myButton:setStrokeColor(180, 180, 180)
– Make a rectangle to act as the other button.
myButton2 = display.newRect(80, 300, 150, 50)
myButton2.strokeWidth = 3
myButton2:setFillColor(140, 140, 140)
myButton2:setStrokeColor(180, 180, 180)
– Add an event listener to the rectangle buttons.
myButton:addEventListener( “tap”, myButton )
myButton2:addEventListener( “tap”, myButton2 )
– Make a variable to illustrate the problem.
myVar = 1
– The button functions, top first then the one below.
function myButton:tap( event )
print (“Im clicking the first button, myButton”)
print ("myVar is set to " … myVar)
myVar = 1
toggleEvent1()
end
function myButton2:tap( event )
print (“Im clicking the second button, myButton2”)
print ("myVar is set to " … myVar)
myVar = 2
toggleEvent2()
end
– Toggling them on and off with the eventlisteners works - but starts to do things twice.
function toggleEvent1()
if myVar == 1 then
print ("I’m toggling, myVar was set to " … myVar)
myButton:removeEventListener( “tap”, myButton )
myButton2:addEventListener( “tap”, myButton2 )
end
end
function toggleEvent2()
if myVar == 2 then
print ("I’m toggling, myVar was set to " … myVar)
myButton:addEventListener( “tap”, myButton )
myButton2:removeEventListener( “tap”, myButton2 )
end
end[/lua]
Any thoughts much appreciated!
[import]uid: 49694 topic_id: 21054 reply_id: 321054[/import]