ContextActionService isn't working

I have a script that when a player presses the “H” key on his keyboard a sound should play locally. But it doesn’t.

This is the script:

local ContextActionService = game:GetService("ContextActionService")
local SoundService = game:GetService("SoundService")

-- A car horn sound
local honkSound = Instance.new("Sound", SoundService)
honkSound.Looped = true
honkSound.SoundId = "rbxassetid://9120386436"

local function handleAction(actionName, inputState, inputObject)
	if actionName == "HonkHorn" then
		if inputState == Enum.UserInputState.Begin then
			honkSound:Play()
		else
			honkSound:Pause()
		end
	end
end

-- When the player sits in the vehicle:
ContextActionService:BindAction("HonkHorn", handleAction, true, Enum.KeyCode.H, Enum.KeyCode.ButtonY)

-- When the player gets out:
ContextActionService:UnbindAction("HonkHorn")

Note: This a LocalScript inside of StarterPlayerScripts. Also, this is the script from the roblox documentation page, but with a little bit of modification from me.

Here is the page:
ContextActionService page

How can fix this?

Firstly, make sure that the sound asset you’re using (rbxassetid://9120386436) is correct. Test it outside of this script to confirm it plays correctly.

Secondly, the sound is set to play on a Begin input state but is paused on any other state. If the key isn’t released properly, or another input interrupts it, the sound might pause unexpectedly.

Thirdly, the ContextActionService’s UnbindAction is called right after BindAction without any conditional check, effectively unbinding the action right after binding it. This means the “H” key won’t trigger the action because it was unbound immediately. The unbinding action should be placed in an appropriate place where it’s called when the player exits the vehicle or does the equivalent action in your game.

Lastly, since this is a LocalScript, it runs on the client (player’s machine). Make sure there’s a client (player) in the game when you’re testing this script, as it won’t run if tested in a server-only environment.

Everything else seems to be great. If none of those helped you then I do not know what Is wrong with it. :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.