Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

how to run an event based on when a key is pressed?

Asked by 4 years ago

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!

3 answers

Log in to vote
1
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

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)
Ad
Log in to vote
0
Answered by 4 years ago

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.

Log in to vote
-1
Answered by 4 years ago
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)
0
attack my reputation for trying to help someone, why don't ya? SKOSHILOKI 67 — 4y
0
He is just a beginner, better explanation than give him script. Block_manvn 395 — 4y

Answer this question