how do i make a script that does something when the "e" key is pressed???
As YBN_oSy said, you need to use the UserInputService
, press here or here to see more tutorials about UserInputService
.
As I can see, you are new to Roblox Lua Scripting, so I will teach you the diference between a LocalScript
and a Script
, so you can understand why this code MUST be in a LocalScript
.
A LocalScript
is a client-side code. What does this mean? This code runs in the client connected to Roblox (the player). This type of code can only run in certain locations and is used to access some client-only objects, for example, the player's keyboard. For more information about LocalScripts
click here.
A Script
is a server-side code. This means that this code runs in the game server. This code can run everywhere and can access some server-only objects, such as ServerStorage
.
Now that you know the Roblox scripting basics, we can start with the code:
----//Getting UserInputService\\---- local UIS = game:GetService("UserInputService") --UserInputService can only be obtained from a LocalScript using :GetService()
Okk, now that we have the UserInputService
stored as a local value, we are going to get the LocalPlayer
.
----//Getting the Player\\---- local plr = game.Players.LocalPlayer -- Gets the client of the script. This can only be done in a LocalScript
Now let's do a code that prints the name of the player when they press a Key
function KeyPressed(press) local key = press.KeyCode --gets the code of the key that the player pressed. if key = Enum.KeyCode.E then --Checks if the key pressed is E. print(plr.Name) --prints the name of the player that pressed E. Open the output to see it. end end UIS.InputBegan:Connect(KeyPressed) --Calls the function
This code should print the name of the player that presses E. Put the code in a LocalScript
inside StarterPlayerScripts
.
The next time you post a question in the scriptinghelpers page, make sure that you give a detailed description of what you want to do, the code you tried and what is wrong with your code.
Sorry if my English is bad, but I am not from a English country.
I hope I helped. For more Roblox Scripting tutorials visit Roblox Studio Wiki, RobloxDev or the scriptinghelpers guide.
You can use the UserInputService for something like this. I don't have enough time to show a link on it, but i'm sure you'll get the gist of the script. Anyways, here's an example:
local UIS = game:GetService("UserInputService") UIS.InputBegan:Connect(function(Input, gameProcessedEvent) -- InputBegan is when the player presses the button if gameProcessedEvent then return end local KeyCode = Input.KeyCode if KeyCode == Enum.KeyCode.E then -- post what you want to happen end end)
Hope this helps,
--Sy