Hi i am making a key bind selection and obviously i dont want the players inputting strings for their key binds and I made a text Box where they input and it checks if it is a character like A or B or C for example and then changes the module script accordingly .
local module = {
InventoryButton = "E"
}
return module
I will add more keybinds for stuff eventually but i want to lay down the groundwork any ideas for me to check if it is a char that is being inputted
TextBoxes have an event “InputBegan.” The parameter it passes is the InputObject, where you can check if the key inputted is A B or C with InputObject.KeyCode
Yes but that checks character length what im asking is there a data type called char because in other languages they have a char data type that can be checked accordingly im trying to check if it is a char and then the input length
local function IsValidKey(key)
key = tostring(key)
key = string.upper(key)
local result = nil
pcall(function()
result = Enum.KeyCode[key]
end)
return result
end
print(IsValidKey("E"))
--> Enum.KeyCode.E
print(IsValidKey("?re"))
--> nil
When the user tries to change their keybind, you can check If it is valid with this function, else you set it back to what it was before or its default key.
You can then use something similar to this (I haven’t checked if it works properly, but you should definitely store the keys in a dictionary like this) when the user inputs a key in the textbox:
local Keys = {
BackpackKey = Enum.KeyCode.E;
SprintKey = Enum.KeyCode.LeftShift;
}
BackpackKeyTextbox.FocusLost:Connect(function()
local validKey = IsValidKey(BackpackKeyTextbox.Text)
BackpackKeyTextbox.Text = (validKey and BackpackKeyTextbox.Text) or DefaultBackpackKey
Keys.BackpackKey = validKey or DefaultBackpackKey
end)
How would you suggest i lay out the module because this is what i did so far using what you sent.
local PlayerKeyBindsModule = require(game.StarterPlayer.StarterPlayerScripts.PlayerKeybinds)
local InventoryKeyCodeLetter = PlayerKeyBindsModule.InventoryKey
local InventoryTextBox = script.Parent.PlayerInventoryBox
local defaultInventoryBind = {
InventoryKeyCode = {
InventoryLetter = InventoryKeyCodeLetter;
InventoryDefaultBind = Enum.KeyCode[InventoryKeyCodeLetter];
};
}
local function IsValidKey(key)
key = tostring(key)
key = string.upper(key)
local result = nil
pcall(function()
result = Enum.KeyCode[key]
end)
return result
end
print(IsValidKey("E"))
--> Enum.KeyCode.E
print(IsValidKey("?re"))
InventoryTextBox.FocusLost:Connect(function()
local validKey = IsValidKey(InventoryTextBox.Text)
InventoryTextBox.Text = (validKey and InventoryTextBox.Text) or defaultInventoryBind.InventoryKeyCode.InventoryLetter
Keys.BackpackKey = validKey or DefaultBackpackKey
end)