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

Help With Key Inputs for numbers?

Asked by 8 years ago

I'm trying to see if when I press 1 or 2 it will do something like print, but when i tried it, it doesn't work. Also this is in Starter Gui and is a local script.

local Mouse = game.Players.LocalPlayer:GetMouse()

Mouse.KeyDown:connect(function(Key)
    if Key == 1 then
        print("Worked")
    end
end)

1 answer

Log in to vote
1
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
8 years ago

Problem

The problem with the script appears to be when you are comparing "Key" to a number, the string can not compare itself to a number value. Also due to KeyDown being outdated, it will not handle some of the game processed keys due to them being used by ROBLOX CoreScripts. So I do recommend the moving toward UserInputService for key events.


Solution

Due to you wanting to print a number key, you would have to disable the CoreGui Backpack with SetCoreGuiEnabled. With that, you would want to encase the 1 between quotes. This way the script will recognize it is comparing a string to a string.


Final Script

game.StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack,false) --Disables the Backpack CoreGui.
game.Players.LocalPlayer:GetMouse().KeyDown:connect(function(k) --Gets the mouse of the LocalPlayer and directly connects it to the KeyDown event.
    if k == '1' then
        print'works!'
    end
end)

UserInputService InputBegan Event

UserInputService is easy to understand once you've tried it once or twice before. With the InputBegan event the script will return two arguments. The first being the InputObject, essentially an array of values that will determine what key is pressed or what input was taken. Whilst the other is GameProcessed, a boolean value that will tell you if the game processed the InputObject and help determine if you should run part of code or not.

Here's a simple script below that will help find if a player hits the / key and to see if the game processed it or not.

game:GetService('UserInputService').InputBegan:connect(function(Input,Processed) --Connect to the Inputbegan event.
    if Input.KeyCode == Enum.KeyCode.Slash and Processed == true then --Verify that the KeyCode the array provides is the same value as the Enumerated KeyCode. Also make sure that Processed equals true.
        print'Player should be typing...' --If both those statements are true, then print this.
    end
end)

Hopefully this answer helped, and if it answered your question do not forget to hit the Accept Answer button. If you have any questions, feel free to ask them in the comments.
Ad

Answer this question