KeyBoard Detection Problems

Salutations, DevForum Members.
For the past 20 minutes or so, I have been working on a little script that is shown below. This script (local script inside of a frame) is doing everything it is meant to except for one thing, which is executing a command when a player presses the ‘Q’ key on their keyboard. I have been searching a little to see what the problem may be however I have not found any crystal clear evidence.

The script also doesn’t display any errors in the Output.

game.Workspace.ToolTriggerEvent.ClickDetector.MouseClick:Connect(function()
	local Player = game.Players.LocalPlayer
	local PlayerGUI = Player:WaitForChild("PlayerGui")
	
	local Mouse = Player:GetMouse()
	local CoolDown = false
		
	local text = "Press 'Q' to turn off flashlight."
	
	for i = 1, #text do
		script.Parent.TextLabel.TextTransparency = 0
		script.Parent.TextLabel.Text = string.sub(text, 1, i)
		wait()
	end
	
	PlayerGUI.FlashlightGUI.Enabled = true
	
	game.Workspace.ToolDisabler1:Destroy()
	game.Workspace.ToolDisabler2:Destroy()
	game.Workspace.ToolTriggerEvent:Destroy()
	
	Mouse.KeyDown:Connect(function(Key)
		if Key:lower() == "q" or Key:upper() == "Q" then
			if CoolDown == false then
				if PlayerGUI.FlashlightGUI.Enabled == true then
					PlayerGUI.FlashlightGUI.Enabled = false
					wait(1)
					CoolDown = false
				else
					PlayerGUI.FlashlightGUI.Enabled = true
					wait(1)
					CoolDown = false
				end
			end
		end
	end)
	wait(2)
	script.Parent.TextLabel.TextTransparency = 1
	script:Destroy()
end)

Yep! The script destroyed itself before detecting the key being pressed, my mistake.

I would personally recommend you utilize UserInputService instead of Mouse KeyDown, as it’s a bit more reliable to run logic on.

Something akin to this should solve your problem:

game:GetService('UserInputService').InputBegan:connect(function(InputObject)
	if InputObject.UserInputType == Enum.UserInputType.Keyboard and InputObject.KeyCode == Enum.KeyCode.Q then
		if CoolDown == false then
			if PlayerGUI.FlashlightGUI.Enabled == true then
				PlayerGUI.FlashlightGUI.Enabled = false
				wait(1)
				CoolDown = false
			else
				PlayerGUI.FlashlightGUI.Enabled = true
				wait(1)
				CoolDown = false
			end
		end
	end
end)

Hope this helps!

1 Like

Hey! I’ll definitely take that into consideration, although the problem is resolved. I do thank you for responding and giving a little feedback on the script!

1 Like