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 comments
I first check if it is not nil and also I do set inputConnection to the UserInputService.InputBegan Connection on line 7
Oh.