UserInputService inside a function is duplicated on each function call

One thing I discovered only today is that if I put for example a UserInputService.InputBegan inside a function, every time I call that function, the InputBegan is duplicated:

local UserInputService = game:GetService("UserInputService")

function test()
	UserInputService.InputBegan:Connect(function(Input)
		print("InputBegan")
	end)
end

test()
test() -- if I include this line, any input will be executed twice...
test() -- here, any keypress will be executed three times... and so on...

Is that a normal behavior?
If yes, how could I “kill” to first InputBegan to avoid this doubled call?

3 Likes
local Input = UserInputService.InputBegan:Wait() -- will only listen once

--same thing but asynchronous ig
local connection
connection = UserInputService.InputBegan:Connect(function(Input)
connection:Disconnect()
end)

don’t know what you are trying to do but here you go

1 Like

I have some UserInputService.InputBegan at different parts of my script: one is to be used when a “free camera” is activated; another is to be used when I’m in another section of the game… and so on…
That’s why I’m using it inside functions, to maintain its scopes.
However, this duplication problem is happening when I call the same function twice or more.
Why?

Is it possible that you can show the entire script. Connecting InputBegan multiple times isn’t a good idea and I can’t think of any instances where it would be necessary. Perhaps I could modify your script so that it is ‘better’

You can “disconnect” a connection using the :Disconnect() function. Just make sure that the connection is stored as a variable:

local connection = UserInputService.InputBegan:Connect(function(input)

end)
connection:Disconnect()
2 Likes

Np, I want to understand the logic of these things…

What’s the reason of the Wait() in the sentence above?

Should I have a single InputBegan for the entire script and there to control the behavior of the key according to the “moment” of the game?
Is there a problem with having multiple ʻInputBegan`?

You shouldn’t have more than one InputBegan events that do the exact same thing, especially if more of them are connected every time the function is called.

What you could try doing is connecting the event when you want it, and disconnecting it when you don’t. Or, if you only want the InputBegan event to fire once then be done, you can :Disconnect() it after it’s fired:

local connection
connection = UserInputService.InputBegan:Connect(function(input)
    -- code
    connection:Disconnect()
end
1 Like

99% sure that will error “attempt to index nil with Disconnect”

1 Like

Yeah, you’re probably right. In that case, it’ll need to look like this:

local connection
connection = UserInputService.InputBegan:Connect(function(input)
    -- code
    connection:Disconnect()
end)

I’ll edit my post too.

1 Like