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

How to check for when a player presses a key(Specifically Enter)?

I tried this

local mouse = game.Players.LocalPlayer:GetMouse()
local function msg(t)
	print("Confirmed"..t)
end
script.Parent.InputBegan:Connect(function()
	msg("inputbegan")
	local clickable = true
	mouse.Button1Down:Connect(function()
		msg("btndown")
		if clickable == true then
			
			local clicked = true
		end
	end)
	mouse.KeyDown:Connect(function(key)
		msg("spacedown")
		if key == Enum.KeyCode.KeypadEnter and clickable == true then
			msg("main") 
			script.Parent.Text = ""
		end
	end)
end)

The confirmed and the msg() function is for testing purposes. All help Appreciated

1 comment

0

2 answers

Instead of using the Mouse object to manage input, it's recommended that you use UserInputService (Or ContextActionService depending on what you're doing).

You would use it like this, to detect the return key:

local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(inputObject)
	--The inputObject passed gives you information on the input
	if inputObject.KeyCode == Enum.KeyCode.Return then
		print("Return key was pressed!")
	end
end)

Also note that input can only be handled on the client, so you must use a LocalScript for this in a place like StarterPlayerScripts.

Well, if you're going to use InputBegan, you have to use UserInputService.

I also recommend UserInputService over Mouse.

Here is how you should be using InputBegan.

local UIS = game:GetService("UserInputService")

local function message(msg)
	if type(msg) == "string" then
		return print("Confirmed: "..msg)
	else
		return warn("Error: String Expected; Got "..string.upper(string.sub(type(msg),1,1))..string.sub(type(msg),2,#type(msg))) --// I just edited this a little bit for fun
	end
end

UIS.InputBegan:Connect(function(input, gameProcessedEvent) --// Usually shortened to 'gpe'
	if input.KeyCode == Enum.KeyCode.Return and not gameProcessedEvent then --// 'Return' is another name for 'Enter'
		print("Pressed Enter")
		message("Enter")
	elseif input.KeyCode == Enum.KeyCode.Space and not gameProcessedEvent then
		print("Pressed Space")
		message("Space")
	elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
		print("Pressed Mouse Button 1")
		message(1)
	end
end)

Hope this helped! Feel free to select this as an answer if this worked for you!

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