What would be a better way of approaching UserInput

This is not a CAS vs UIS debate, it’s just help with UIS for now.

How could I approach using UIS? I mean with organization. Typically, people just tell you to do something like

local UIS = game:GetService("UserInputService")

UIS.InpuBegan:Connect(function()
   if Input.KeyCode = Enum.KeyCode.Q then
       print("Q has been pressed")
   end
end)

Which has nothing wrong with it, but I’m trying to figure out a better way of organizing my Keycodes, so it’s not just a bunch of if statements. Is it possible to have this with just one event?

This is what I came up with. It is slightly more Organized.

lcoal Key = "E"
local UIS = game:GetService("UserInputService")

local function KeykindHandler(Input, Correct)
	if Input.KeyCode == Enum.KeyCode[Correct] then
		return true
	else
		return nil
	end
end


UIS.InputBegan:Connect(function(Input)
	local Sucess = KeykindHandler(Input, Key)
	if Sucess then
		print("Pressed E!")
	end
end)
2 Likes

You could create a dictionary which contains each keycode and a callback function to run. I understand you want to use UIS but input organization can be achieved much more easily with CAS. @EmbatTheHybrid took the time to write some code for this so I would check their post out.

UIS will require if statements because of how it works. It’s an event that fires when any input is received. If you have a lot of inputs I would just use CAS as it can handle inputs much better.

2 Likes

Yep can confirm, an example is this vehicle input module I found in community resources which I tried to explain here:

2 Likes

Not sure how much this would help, but if you want, you could maybe put the functions connected to keycodes into a Dictionary wher ethe key to press is the key, and the function is value in that key,

local UIS = game:GetService("UserInputService")

local functions = {
	[Enum.KeyCode.Q] = function()
		print("Q has been pressed")
	end,
	[Enum.KeyCode.E] = function()
		print("THE E HAS BEEN PRESSED")
	end
}

UIS.InputBegan:Connect(function(input,gpe)
	local func = functions[input.KeyCode]
	if not func or gpe then return end
	func()
end)

It could prove to be a simpler way, although I’m unsure since if your functions are long, you will in the end have a long dictionary as well, but it will undoubtedly be better than a long InputBegan event.

I know this goes against what you said, but you could put your InputBegans into separate localscripts for specific uses, (Key handling for dashing, key handling for Pick up keycodes, etc). But in the end it’s how you want to do it in the end, there’s no right or wrongs, there’s only messy and organized (unless of course your code can be optimized in which case go for it)

I know i’m late to the party but just wanted to conclude details

8 Likes