Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

[Answered] Why is this InputBegan function not able to be disconnected?

In my script I am using InputBegan to detect if the players presses 'E' when they are within 10 studs of an NPC. It works fine except that when they are farther then 10 studs it should disconnect but when I press E the event still fires. I am not getting any errors.

local inputConnection = nil
RunService.RenderStepped:Connect(function()
	local dist = (rootPart.Position - npcRootPart.Position).magnitude
	if dist < 10 then
		button.Enabled = true
		
		inputConnection = UserInputSerivce.InputBegan:Connect(function(input)
			if input.KeyCode == Enum.KeyCode.E then
				print("E Pressed")
			end
		end)
	else
		if inputConnection then 
			inputConnection:Disconnect()
			inputConnection = nil
		end
		button.Enabled = false
	end
end)

2 answers

Hello. The reason is that if the dist was under 10, it would try and disconnect the inputConnection, but it would be nil since the inputConnection had not been defined.

2 comments

0

I first check if it is not nil and also I do set inputConnection to the UserInputService.InputBegan Connection on line 7

0

Oh.

So I figured out that the problem was that I was assigning inputConnection to a new connection each frame so when I would try to disconnect it would just disconnect the latest connection that was created but still kept multiple other connections that were created.

This discussion is preserved as it was. New answers, comments, and votes are closed.