ContextActionService bind automatically runs?

I have a tool that binds a function with contextactionservice everytime somebody is near

local plr = game.Players.LocalPlayer
local tool = script.Parent
local handle = tool.Handle
local mouse = plr:GetMouse()
local CS = game:GetService("ContextActionService")
local Eq = false
local Loop = false
local Used = false
local MaxDistance = 20

local function onD()
	print("D")
end
tool.Equipped:Connect(function()
	Eq = true
	while wait() do
		if not Eq then break end
		for _,object in pairs(workspace:GetChildren()) do
			if object:FindFirstChild("Humanoid") and object ~= plr.Character then
				if (object.HumanoidRootPart.Position - handle.Position).magnitude <= MaxDistance then
					local RootPart = object.HumanoidRootPart
					CS:BindAction("MDetain",onD,true,"t")  --Here
					break
				else
					pcall(function()
						CS:UnbindAction("MDetain")
					end)
				end
			end
		end
	end
end)

tool.Unequipped:Connect(function()
	Eq = false
	Used = false
end)

The Problem seems to be at

CS:BindAction("MDetain",onD,true,"t") 

Everytime I equip the tool and somebody is near me then it automatically runs the function even though I didnt press T

1 Like

you should probably use the Enum.KeyCode instead of a string, idk if this changes anything but try it, I guess

I already tried Enum.KeyCode. . .

Try replacing onD with this:

local function onD(ActionName, InputState)
    if ActionName == "MDetain" and InputState == Enum.UserInputState.Begin then
        print("D")
    end
end

Yes, as @E44ORSANS says, as you are probably getting a Cancel InputState.
On unequip, you might want to Unbind as well if bound to make it cleaner.