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?
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
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ā
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