ContextActionService: How do I prevent a Context Action from firing twice?

Well, this is a big one.

Every time I try to use CAS for controlling the game, I always end up with an action happening twice, rather than once. For example:


local CAS = game:GetService("ContextActionService")

local function printOnce()
      print("this is supposed to print once")
end

CAS:BindAction("print",PrintOnce,false,Enum.KeyCode.Return)

Output:

this is supposed to print once (x2)

Now, I tried Enum.UserInputState.Begin or UIS.InputBegan, but it didn’t help.

Any suggestions?

2 Likes

CAS has its own user input state which is passed to the function being binded. The devhub example code on ContextActionService | Roblox Creator Documentation should work.

local ContextActionService = game:GetService("ContextActionService")
 
-- Setting up the action handling function
local function handleAction(actionName, inputState, inputObj)
    if inputState == Enum.UserInputState.Begin then
        print("Handling action: " .. actionName)
    end
 
	-- Since this function does not return anything, this handler will
	-- "sink" the input and no other action handlers will be called after
	-- this one.
end
 
-- Bind the action to the handler
ContextActionService:BindAction("BoundAction", handleAction, false, Enum.KeyCode.F)
2 Likes

Ah, I noticed the problem I was making all the time!

I forgot to add the parameters, that’s why it failed.