Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I tell if someone presses a key?

Asked by
Kratos232 105
9 years ago

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

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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.

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? Kratos232 105 — 9y
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 adark 5487 — 9y
Ad
Log in to vote
0
Answered by 9 years ago

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)

Answer this question