Using Key Detection

This will teach you key detection for LUA.

by brokenVectors

Author Avatar

Introduction

Key detection is when you detect the event of pressing a key, or letting go of it.

How do I do it?

Actually, there are two ways to do it. You could use UserInputService, or using ContextActionService. ContextActionService is useful for mobile support, like making a button that makes your character change colour.

--NOTE: If you're using key detection, it will only apply for one player, meaning it needs to be in a client
--directory, like StarterGui, StarterPack, StarterPlayerScripts.

--Method 1:

local userInputService = game:GetService('UserInputService')

userInputService.InputBegan:Connect(function(input,obj)
    local key = input.KeyCode
    if key == Enum.KeyCode.E and not obj then
        print('Player is pressing the E key')
    end
end

userInputService.InputEnded:Connect(function(input)
    local key = input.KeyCode
    if key == Enum.KeyCode.E then
        print('Player has let go of the E key')
    end
end
--Method 2:
local contextActionService = game:GetService('ContextActionService')
function EKey(actionName,inputState,obj)
    if not obj then
        if inputState == Enum.UserInputState.Begin then
            print('Player is pressing the E key')
        elseif inputState == Enum.UserInputState.End then
            print('Player has let go of the E key')
        end
    end
end

contextActionService:BindAction('PrintE',EKey,false,Enum.KeyCode.E) --Argument 1: Action name, Argument 2: Function to bind, Argument 3: Create touch button for mobile, Argument 4: Which key to bind

How does it work?

In method 1, InputBegan and InputEnded are both events, that are being connected to an anonymous function. In the function for InputBegan, it checks if obj is nonexistent. Obj is a variable that tells us whether the player is hovering over a gui, or typing in a textbox. And of course, it checks if the player is pressing the E key.

But what about method 2?

In method 2, it's making a function that checks if the inputState is Begin or End. It's self-explanatory, because it's Begin if you're pressing the key, and it's end when you let go. Then, it's binding it to when you're pressing E, binding it to the function EKey, calling the action EPrint.

How is this useful?

Imagine if you wanted to make it so that when you pressed R with your gun equipped it would reload. You will need to use key detection! Or maybe when you press C, it will make you crouch! Still, you need to use key detection!