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

Testing a specific key pressed (Ideas?)

I'm currently making a new game and I want the player to be able to press keys to trigger events. One of the things I want to add is hotbar access via 1-9 keys. Something simple to do is just copy and paste the key detection code over and over, but I want it to take up less space and so I can change what key pressing does easily. So I made this-

local keyList = {'One','Two','Three','Four','Five','Six','Seven','Eight','Nine'}

function onKeyPress(inputObject, gameProcessedEvent)
	for i=1,9 do
		print(inputObject.KeyCode,"Enum.KeyCode." .. keyList[i])
		if inputObject.KeyCode == "Enum.KeyCode." .. keyList[i] then
			print(keyList[i] .. " pressed")
		end
	end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)

But it does nothing, not even throw an error, even though they look exactly the same. I don't know what is going on, the wiki is no help and the Roblox forums are offline forever. Any suggestions on what to do?

1 answer

Rather than using Enum.KeyCode, you can use a number, since every enum stands for a number, e.g

301 --> Caps Lock key

The number Enums range from 48 to 57 inclusively, where 48 is the Zero key and 57 is the Nine key.

function onKeyPress(inputObject, gameProcessedEvent)
	if gameProcessedEvent then return end
	for i = 48,57 do
		if inputObject.KeyCode.Value == i then
			print(inputObject.KeyCode.Name .. " pressed")
		end
	end
end

game:GetService("UserInputService").InputBegan:Connect(onKeyPress)

1 comment

0

Thanks so much dude, I got stuck searching for the wrong thing for so long that I didn't even know this existed!

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