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

Why does my code not work, it's printing Enum.KeyCode.Unknown, why is that?

I'm trying to get which key the character is pressing down without using both InputBegan and InputEnded. I'm trying to do it in a more clever way, but the problem is that it's not registering any of the keys I'm pressing, all it's printing is: Enum.Keycode.Unknown

-- Services
local UserInputService = game:GetService("UserInputService")


local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")
humanoid:ChangeState(Enum.HumanoidStateType.Physics)

local ButtonsHeld = {}
local MoveVector = Vector3.new()
local MoveVectors = {
	[Enum.KeyCode.W] = Vector3.new(0, 0, -1),
	[Enum.KeyCode.A] = Vector3.new(-1, 0, 0),
	[Enum.KeyCode.S] = Vector3.new(0, 0, 1),
	[Enum.KeyCode.D] = Vector3.new(-1, 0, 0),
}

function onInputChanged(input, gameProcessed)
	print(input.KeyCode)
	if (MoveVectors[input.KeyCode]) and (input.UserInputType == Enum.UserInputType.TextInput) then
		if (input.UserInputState == Enum.UserInputState.Begin) then
			if (not ButtonsHeld[input.KeyCode]) then
				ButtonsHeld[input.KeyCode] = true
				MoveVector = MoveVector + MoveVector[input.KeyCode]
			end
		elseif (input.UserInputState == Enum.UserInputState.End) then
			if (ButtonsHeld[input.KeyCode]) then
				ButtonsHeld[input.KeyCode] = false
				MoveVector = MoveVector - MoveVector[input.KeyCode]
			end
		end
	end
end

UserInputService.InputChanged:Connect(onInputChanged)

3 comments

0

try using tostring() for the print

0

when the mouse is clicked or a unknown button ex: function button on laptops is pressed it will be a unknown keycode

0

Better question is, why dont you want to use imput began and imput ended. This is literally why they exist.

1 answer

If you'd like to check if a key is being held down without using InputBegan or InputEnded, you can use UserInputService:IsKeyDown(). For your input table, it would be something like this:

while true do
	MoveVector = Vector3.new()
	for e, v in pairs(MoveVectors) do -- checks every KeyCode and its associated movement vector in the MoveVectors table, "e" being the KeyCode and "v" being the vector
		local held = UserInputService:IsKeyDown(e)
		ButtonsHeld[e] = held
		if held then
			MoveVector = MoveVector + v
		end
	end
	wait()
end

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