We use cookies on this site to enhance your user experience

Tool Recipe – ContextServiceAction Bind

Tool Recipe – ContextServiceAction Bind

Problem

You want to bind user input like a key press to a Tool. In this example, the context is a weapon being equipped and the action is reloading the weapon.

Solution

Test this code by pasting it into a LocalScript within a Tool.

-- Inside a LocalScript
local tool = script.Parent

local ContextActionService = game:GetService("ContextActionService")

local ACTION_RELOAD = "Reload"

local function handleAction(actionName, inputState, inputObject)
	if actionName == ACTION_RELOAD and inputState == Enum.UserInputState.Begin then
		print("Reloading!")
	end
end

tool.Equipped:connect(
	function()
		ContextActionService:BindAction(ACTION_RELOAD, handleAction, true, Enum.KeyCode.R)
	end
)

tool.Unequipped:connect(
	function()
		ContextActionService:UnbindAction(ACTION_RELOAD)
	end
)

Discussion

This recipe depends mainly on ContextActionService. When the tool is equipped, a “reload” action is bound, and when the tool is unequipped, the same action is unbound. When the player presses R with the tool equipped, the message “Reloading!” will appear.