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

How to detect for enter key being pressed?

Has anybody got the code for detecting the enter key pressed. I've tried all the things on the forums but they just don't do anything.

If someone can help me out that would be appreciated Thanks!

2 comments

0

Although these 2 people answered your question, I'd like for you to know that in order for you to ask a question here, you'd need to supply your own code for us to FIX not make. Since this is already answered there's nothing we can do but if we catch it your question may be removed.

0

Also, there are 3 ways of doing it. KeyDown(Deprecated; it probably shouldn't be used anymore), UserInputService, and ContextActionService. Since there are 2 posts about KeyDown and UserInputService, you might also wanna check out this: http://wiki.roblox.com/index.php?title=API:Class/ContextActionService

3 answers

The following code will print something when the R key is pressed.

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.R then
		print("R was pressed")
	end
end
 
game:GetService("UserInputService").InputBegan:connect(onKeyPress)

Basically you'd be using the UserInputService and when InputBegan is fired it'd run OnKeyPress() and then you would check which key was clicked which in this example is 'R' using

if inputObject.KeyCode == Enum.KeyCode.R then

then you'd run your code

This example prints 'R was pressed' when the R key is clicked and prints 'Q was pressed' when the Q key is pressed.

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.R then
		print("R was pressed")
       elseif inputObject.KeyCode == Enum.KeyCode.Q then
		print("Q was pressed")
	end
end
 
game:GetService("UserInputService").InputBegan:connect(onKeyPress)

Sourse http://http://wiki.roblox.com/index.php?title=Keyboard_input

The key code pages gives you codes for keys like Enter and Tab

Key Codes http://wiki.roblox.com/?title=API:Enum/KeyCode Hope this helped.

2 comments

0

do I just replace R with 13

0

No, Enum.KeyCode.Return has value 13. Use that instead; much more straightforward.

You can use the following to detect for the enter key

local UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(function(input,GPE)
	if input.KeyCode == Enum.KeyCode.Return then
		-- do the action here
	end
end

The keycode for enter is 13, it would be used like this

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
 
Mouse.KeyDown:connect(function(Key)
	if Key == 13 then
		--Code
	end
end)

I do not recommend using KeyDown, as it has been deprecated

1 comment

1

I also would not recommend it. Do not provide answers which use deprecated functions, even if they do include disclaimers.

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