Gui toggle keybind script wont work

Can someone explain why this wont work

its a toggle with a keybind the player can switch

local Mouse = game:GetService("Players").LocalPlayer:GetMouse()
local KeyBind = script.Parent.KeyBind.LocalScript.Keybind
local toggle = false

KeyBind.Changed:Connect(function(newVal)
	if newVal == KeyBind then
		game.ContextActionService:UnbindAction("keyPress")
	end
end)

function onKeyPress(actionName, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		print("pressed")
		if toggle == false then
			toggle = true
			print("on")
			print(KeyBind.Value)
		else
			toggle = false
			print("off")
			print(KeyBind.Value)
		end
	end
end

game.ContextActionService:BindAction("keyPress", onKeyPress, false, KeyBind.Value)

this is a string value “local KeyBindValue = script.Parent.KeyBind.LocalScript.Keybind”

ive been trying to make this work for 6 hours now

1 Like
local Mouse = game:GetService("Players").LocalPlayer:GetMouse()
local KeyBind = script.Parent.KeyBind.LocalScript.Keybind
local toggle = false

Mouse.KeyDown:Connect(function(k)
	if k == KeyBind and not toggle then
		print("pressed")
		toggle = true
		print("on")
		print(KeyBind)
	else
		toggle = false
		print("off")
		print(KeyBind)
	end
end)
1 Like

I’m not sure how to use BindAction, but here’s with UserInputService:

local UIS = game:GetService("UserInputService")
local KeyBind = script.Parent.KeyBind.LocalScript.Keybind
local toggle = false

UIS.InputBegan:Connect(function(key, typing)
	if not typing and key.KeyCode == Enum.KeyCode[KeyBind.Value] then
		toggle = not toggle
		print(toggle and "on" or "off")
		print(KeyBind.Value)
	end
end)

Also, I’m assuming the KeyBind Value is the name/key

i had to fix some stuff but thanks i learned somthing thanks