Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I use a function when a player presses a button?

Title says it all, so how do I fire a function when the player presses a button on their keyboard, I couldn't find any events in the play about this... Idk how to do this...

1 answer

✓ Accepted answer

You would use a LocalScript in StarterPlayerScripts, under StarterPlayer.

You could then get the Mouse object from the LocalPlayer, and connect the KeyDown event to a function.

--LocalScript in StarterPlayerScripts in StarterPlayer folder

player = game.Players.LocalPlayer
mouse = Player:GetMouse()

function onKeyDown(key)
	print(key)
	if key == "e" then
		player.Character.Humanoid.Walkspeed = 30 --Or something like that
	end
end

mouse.KeyDown:connect(onKeyDown)

An alternative is to use the UserInputService:

--Same thing as last time, a LocalScript in StarterPlayerScripts in StarterPlayer

player = game.Players.LocalPlayer
inputservice = game:GetService("UserInputService")

function onInputBegan(input)
	if input == Enum.KeyCode.E then
		player.Character.Humanoid.Walkspeed = 30
	end
end

inputservice.InputBegan:connect(onInputBegan)

1 comment

1

Lol, I didn't know the mouse was for the keyboard too...

This discussion is preserved as it was. New answers, comments, and votes are closed.