userInputService:GetStringForKeyCode() not returning string for LeftAlt or LeftShift

I’m trying to set up customizable keybindings for my game, and they work properly IF the custom keybind is a letter, but if it’s something like LeftAlt or LeftShift then for some reason, the GetStringForKeyCode() method doesn’t return a string for those.

Here’s the function I’m using for keybindings. It works properly except for what I mentioned above:

function InputController.onInputBegan(input, gameProcessed)
	if gameProcessed then return end
	
	if input.UserInputType == Enum.UserInputType.Keyboard then
		local inputKeyCodeString = userInputService:GetStringForKeyCode(input.KeyCode)

		print(inputKeyCodeString, cameraLockKeyCode.Value)

		if inputKeyCodeString == cameraLockKeyCode.Value then
			cameraLockEvent:Fire()
		elseif inputKeyCodeString == targetLockKeyCode.Value then
			targetLockEvent:Fire()
		end
	elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
		primaryAttackEvent:Fire()
	end
end

The print() you can see prints out letters just fine when they are pressed for inputKeyCodeString, but when LeftAlt or LeftShift is pressed, it prints an empty string for that value. It prints cameraLockKeyCode.Value out properly as LeftAlt, so I don’t know what I’m doing wrong. Again, the events under the if checks fire properly if the custom keybinding is set to a letter like Q.

This is weird behavior and probably a bug, but for now you can use this to get the string name instead.

local str = uis:GetStringForKeyCode(input.KeyCode)
str = str ~= "" and str or input.KeyCode.Name

Updated a bit so the keyboard localizing still works relatively the same.
(as per what @DrKittyWaffles said)

1 Like

I don’t think you need to worry about keyboard layout localization for the modifier keys. Why not just add another elseif case for them?

The UserInputService::GetStringForKeyCode function is for localizing inputs to the user’s keyboard layout.

ex. Suppose you have an action that occurs when the user presses the “Q” key on their keyboard. The Q key is in different positions on an AZERTY and QWERTY keyboard layout, but it is inconvenient to have users press different locations on their keyboard, so instead you use this function to tell the user to press the the “A” key on an AZERTY layout and the “Q” key on a QWERTY layout.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.