Keyboard Input

To detect when a player pushes a certain key

by PingyPenguin7

Author Avatar

Making the function

NOTE: There is another way to do this, but I prefer this way.

The first thing you do is create a new LocalScript(IT MUST BE LOCALSCRIPT) and place it in StarterPack.

To begin your script, first you need to make a new function. Call it KeyPress (or something like that)

In the parameters(or parentheses), add one called "input" and one called "gameProcessed".

local function KeyPress(input, gameProcessed)

end

Then, create a new if statement like the one below.

function KeyPress(input, gameProcessed)
    if input.KeyCode == Enum.KeyCode.T then
    end
end

This if statement is detecting if the key that the user presses is equal to the key you want to be pressed.

The Input.Keycode represents the actual key the user pressed.

The Enum.Keycode represents what key you want to be presses. I chose T for my example, but you can use pretty much any key.

After this, there are loads of possibilities you can do with this function, but for now we're gonna put a simple print function.

function KeyPress(input, gameProcessed)
    if input.KeyCode == Enum.KeyCode.T then
        print("T was pressed")
    end
end

Change the 'T' part of the print function to whatever key you want to be pressed. Also, here is one of the possibilities you can do with Keyboard Input:

function KeyPress(input, gameProcessed)
    if input.KeyCode == Enum.KeyCode.T then
        local explosion = Instance.new("Explosion",game.Workspace)
        explosion.Position = game.Players.LocalPlayer.Character.Head.CFrame.Position
    end
end

If you press T, you explode!

Calling the function

Alright, so we made the actual function itself, but now we need to make it happen by calling it!

We call it by using this line of code:

game:GetService("UserInputService").InputBegan:Connect(KeyPress)

The game:GetService("UserInputService") gets the service required to make keyboard input, and the InputBegin detects when the user presses a key on the keyboard.

Complete Script

The entire script should look like this:

function KeyPress(input, gameProcessed)
    if input.KeyCode == Enum.KeyCode.T then

        print("T was pressed")
    end
end

game:GetService("UserInputService").InputBegan:Connect(KeyPress)

Congrats, you've just learned Keyboard Input and how to use it! (hopefully :D)

View in-game to comment, award, and more!