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?

2 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