luaroblox

Roblox ContextAction triggers twice


I tried to use Roblox ContextActionService to create a button in Roblox for mobile but whenever I press the GUI button it triggers and when I release the button it triggers too. I want it to only trigger once when I press the button.

function tpggle()
    print("L pressed")
end
ContextActionService:BindAction("ToggleLight", tpggle, true, Enum.KeyCode.L)
ContextActionService:SetTitle("ToggleLight","L")
ContextActionService:SetPosition("ToggleLight",UDim2.new(1, -97,1, -133))

I expected:
  L pressed
I got:
  L pressed(x2)

Solution

  • Your action handler tqggle is most likely called twice. Once for pushing the button, once for releasing the button.

    Try this:

    function tpggle(actionName, inputState, inputObj)
      if inputState == Enum.UserInputState.Begin then 
        print("L pressed")
      end  
    end
    

    So it will only print something if you push the button.

    Refer to

    https://developer.roblox.com/en-us/api-reference/function/ContextActionService/BindAction

    https://developer.roblox.com/en-us/api-reference/property/InputObject/UserInputState