Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I run a script when a key is pressed ?

Hi, I want to make a script which runs when a Key is pressed down. How can I make it ? I have this :

local UserInputService = game:GetService('UserInputService') local key = 'Enum.KeyCode.Q' -- Use local when Global variables aren't needed
-- Use WaitForChild() on children local Handbook = game.StarterGui:WaitForChild("Handbook") local StartMenue = Handbook:WaitForChild("StartMenue") local GameFrame = StartMenue:WaitForChild("GameFrame") UserInputService.InputBegan:Connect(function(input)
-- Turn the KeyCode Enum into a String
-- Match it to our key
if tostring(input.KeyCode) == key then
-- You can substitute the if statements with the reverse of visible GameFrame.Visible = not GameFrame.Visible end end)

2 comments

0

Just make a function.

0

what is this question? this should work what are you asking?

2 answers

✓ Accepted answer

Do not make an Enum a string, as there is no point in doing so. You can simply use the input parameter like so (Local Script):

local UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(function(input, GPE)
    if not GPE then
	    if input.KeyCode == Enum.KeyCode.Q then
		    -- Do something
	    end
    end
end)

You can simply check if the KeyCode is equal to an Enum. There is absolutely no point in making it a string.

1 comment

0

local Handbook = game.StarterGui.Handbook.StartMenue.GameFrame local UIS = game:GetService("UserInputService") UIS.InputBegan

What did I wrong ?

local Handbook = game.StarterGui.Handbook.StartMenue.GameFrame
local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input, GPE)
    if not GPE then
	    if input.KeyCode == Enum.KeyCode.H then
		    Handbook.Visible = true
		    end
	    end
    end
end)

1 comment

0

Access Handbook via the LocalPlayer's PlayerGui.

This discussion is preserved as it was. New answers, comments, and votes are closed.