KeyCode Script Organization Help

I am currently working on an Anime RPG game that uses the idea of “classes” with multiple abilities. One of the challenges I have faced as a Scripter is trying to keep my Client Side of my code clean and organized and easy, fast to edit.


This is how my LocalScripts are structured:

   [ Variable Referencing / Services ]

   [ KeyCode R ] (For PC)
   [ KeyCode ButtonY ] (For Xbox)
   [ MouseButton R ] (For Mobile)

(then repeat for all the other keys/abilities)

Each KeyCode or MouseButton has 20 - 30 lines of code depending on the ability, (Yes I am using FE lol.) and your “classes” has like 5 - 6 moves you end up with hundreds of lines of horrid code. It has been VERY annoying to work with it and you have to do mindless scrolling to fix something very minimal, is there any way I can merge all these functions for different platforms into just 1 single function?

2 Likes

yes, try this

local inputs = {
     ability1 = {Enum.KeyCode.E, Enum.KeyCode.R};
     ability2 = {Enum.KeyCode.F};
     ability3 = {Enum.KeyCode.Y};
}

local function findAbility(keyCode)
     for ability, v in pairs(inputs) do
          if table.find(v, keyCode) then
               return ability
          end
     end
end
game:GetService("UserInputService").InputBegan:Connect(function(input, isTyping)
     if isTyping then return end
     local abilityName = findAbility(input.KeyCode)
     if abilityName == "ability1" then
     print("do stuff for ability 1")
     elseif abilityName == "ability2" then
     --(...)
     end
end)
3 Likes

Exactly something I was looking for! I didn’t think of the idea of putting them into tables, doing a bit of more module work would certainly make this work, thank you!

2 Likes