I'm trying to make a script that is ran through an event for when you press a certain key.
It's like
if certain key is pressed then run script
it seems events are my weak point, hahaha!
You can use UserInputService’s .InputBegan
signal to run an event when any form of input is detected—you can see all the potential inputs in the hyperlink provided. This event returns two parameters, InputObject
, as the userdata of input received, and GameProcessed
, a Boolean allowing us to denounce if that Input is being handled by a ROBLOX core service; E.g. prevent the event from running if we’re typing in chat, or pressing esc
.
You can use the .KeyCode
property to match the Input type to it’s respective Enum, meaning if we are dealing with a Keyboard Input, we can detect a certain KeyStroke.
local UserInputService = game:GetService("UserInputService") UserInputService.InputBegan:Connect(function(InputObject, GameProcessed) if (GameProcessed) then return end if (InputObject.KeyCode == Enum.KeyCode.Q) then print(game.Players.LocalPlayer.Name.." pressed Q!") end end)
For this you need UserInputService
UserInputService is basically just a service for detecting player actions through a keyboard/gamepad/controller etc. Here is a script for a basic function using input service to print when the letter E is pressed
Note: This would be located in a local script obviously
local UserInputService = game:GetService('UserInputService') UserInputService.InputBegan:Connect(function(input, gameProcessed) if not UserInputService.TextBoxFocused then --Checks if the player is typing if input == Enum.KeyCode.E then print('pressed E') end end end)
You can use this to figure out how to run your event.
game:GetService("UserInputService").InputBegan:Connect(function(input) if input.UserInputType == "Keyboard" and input.KeyCode == "G" then --replace "G" with the key you want --do stuff here end end)