LuaU script (Roblox), how can I make a Key get pressed with a script

3.8k Views Asked by At

An example would have been like

local E = game:GetService('UserInputService').SetKeyDown(Enum.KeyCode.E) 

but it doesnt work ofcourse because i cant jsut make my game press E by itself with this thing, so it requieres soemthing longer and if you find the solution can you also do one where it makes it pressed down?

2

There are 2 best solutions below

2
On

The input can only be registered on the client, therefore you will have to code in a LocalScript. There are 2 services which are used to get the player's input:-

This example shows how to use the UserInputService in getting the player's LeftMouseButton input.

local UserInputService = game:GetService("UserInputService")
 
local function onInputBegan(input)
    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        print("The left mouse button has been pressed!")
    end
end
 
UserInputService.InputBegan:Connect(onInputBegan)

This example properly shows how to use ContextActionService in binding user input to a contextual action. The context is the tool being equipped; the action is reloading some weapon.

local ContextActionService = game:GetService("ContextActionService")
 
local ACTION_RELOAD = "Reload"
 
local tool = script.Parent
 
local function handleAction(actionName, inputState, inputObject)
    if actionName == ACTION_RELOAD and inputState == Enum.UserInputState.Begin then
        print("Reloading!")
    end
end
 
tool.Equipped:Connect(function ()
    ContextActionService:BindAction(ACTION_RELOAD, handleAction, true, Enum.KeyCode.R)
end)

You should take a look at the Wiki pages.

4
On

It sounds like you want to write a script to press the E key, but that isn't possible.

You can bind actions to keypresses, just like in the examples Giant427 provided, and you can also manually call the functions that are bound to those actions, but you cannot write a script to fire keyboard inputs.