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 tell if someone presses a key?

Hey. I'm making a custom Chat GUI, and I can't figure out how to tell when someone presses a key. It's not going to be using ROBLOX's chat, because I'm going to mute everyone by putting a LocalScript in StarterGui to remove all their coreGui things.

I have all the GUIs, but I don't know how to make it tell when someone types something, so that it can type it.

I tried all sorts of things, like Mouse.KeyDown, but they don't work if you press I, O, or use Caps.

So how can I tell if they press any key. I know it's possible, I've seen these kinda GUIs before.

  • Kratos232

2 answers

✓ Accepted answer

Try using the UserInputService!

In a LocalScript, of course:

local uis = game:GetService("UserInputService")
uis.InputBegan:connect(function(inst) --similar to KeyDown
	if inst.UserInputType = Enum.UserInputType.Keyboard then
		if inst.KeyCode = Enum.KeyCode.I then
			print("'I' was pressed!")
		end
	end
end)
uis.InputEnded:connect(function(inst) --similar to KeyUp
	if inst.UserInputType = Enum.UserInputType.Keyboard then
		if inst.KeyCode = Enum.KeyCode.O then
			print("'O' was released!")
		end
	end
end)

You can also use the UIS to hook up Touch events for mobile games, and connect mouseclick events within those two functions.

There are some finicky bits, such that Caps Lock or the other toggle keys fire InputBegan and Ended based on their toggle state, instead of the actual keypress, but it's pretty simple overall.

IIRC, these events can also be used from GUI objects themselves. Using the UIS directly is akin to using GetMouse to get the Player's Mouse without having to use a Tool.

2 comments

1

Is it possible to get it to tell what Key it is, without the Enum thing, or tell if Shift is being pushed? Or make backspaces work?

0

No, yes, and yes. Trust me, using the Enums is better since it's readable. As for backspace or shift: Enum.KeyCode.LeftShift (or RightShift), and Enum.KeyCode.Backspace

One way around this problem is to use a TextBox so that the player's can actually type in the box. All you would have to do is when they hit enter, you set the next chat message as the text of the Chat Box. This piece of code can help you with creating a new message when they hit enter.

function FUNCTION NAME(enterPressed)
	if (enterPressed) then
		--create new message and set text to the current text of the Chat Box
		--set Chat Box text back to "Type here" or something else
	end
end

BOX THAT PEOPLE TYPE INTO.FocusLost:connect(function(enterPressed)
	FUNCTION NAME(enterPressed)
end)

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