how to make a script happen when a button is pressed on the keyboard?
2 Likes
You can easily use UserInputService
for this.
here is an example:
local u = game:GetService("UserInputService")
u.InputBegan:Connect(function(input) -- input is when you press a key
if input.KeyCode == Enum.KeyCode.E then -- click E
print("e was pressed")
end
end)
API documentation: https://developer.roblox.com/en-us/api-reference/class/UserInputService
6 Likes
- You can try to make a script that relates specifically to the button and turn it off. And create another script that enables the first script When the button is clicked.
- Also You can try to use a Module Script. You can use Module Script to access other scripts using the button function .
1 Like
-- We will print 'I like coding' when we press E
-- Script location = StarterPlayerScripts
local UserInputService = game:GetService("UserInputService")
UserInputService.InputBegan:Connect(function(Key) -- Input detected!
if Key.KeyCode == Enum.KeyCode.E -- Checking if input is 'E'
then
print("I like coding") -- Input is 'E', we can print 'I like coding'
end
end)
-- We will print 'Hello, developer' when a input is ended
UserInputService.InputEnded:Connect(function()
print("Hello, developer")
end)
-- This will print after any key or even the E event we wrote above (inputs)
7 Likes