How to disconnect a function

So I’m making a weapon for a game and the gun breaks every time you shoot and unequip it. I tried disconnecting the function but I just get an error in output.

The code goes something like this

local Plr = game:GetService("Players").LocalPlayer
local Mouse = Plr:GetMouse()

local function Shoot()
-- do stuff
end

local function WeaponUnequipped()
Shoot:Disconnect()
end

script.Parent.Unequipped:Connect(WeaponUnequipped)
Mouse.Button1Down:Connect(Shoot)

I receive "Attempt to index function with ‘Disconnect’ upon firing this code.
This code is in a local script in a tool.

Just do

return

--// instead of (it needs to be inside the functions that you want to "Disconnect") 
:Disconnect

Inside of the function WeaponUnequipped()?

Check my latest edit :slight_smile:.

The Connect() function, if I recall, returns an object, which is the event. That object has the Disconnect() function. So you can try this:

local Plr = game:GetService("Players").LocalPlayer
local Mouse = Plr:GetMouse()
local ShootEvent -- Variable for the event

local function Shoot()
-- do stuff
end

local function WeaponUnequipped()
ShootEvent:Disconnect() -- Use the event variable instead of function.
end

script.Parent.Unequipped:Connect(WeaponUnequipped)
ShootEvent = Mouse.Button1Down:Connect(Shoot) -- Returns the event.
1 Like
local Plr = game:GetService("Players").LocalPlayer
local Mouse = Plr:GetMouse()
local Connection = nil

local function Shoot()
   -- do stuff
end

local function WeaponUnequipped()
    Connection:Disconnect()
end

script.Parent.Unequipped:Connect(WeaponUnequipped)
Connection = Mouse.Button1Down:Connect(Shoot)

this is how to disconnect, you should use return like @caviarbro said instead tho

2 Likes

I recommend using “Maid” by Quenty

Its really practical

2 Likes

Where does it need to be tho, start or end of the function

1 Like

Try to look on this topic I had similiar problem months ago.

1 Like

if you want to break a function just use “return”
if you disconnect then you need to reconnect which is dumb

1 Like

Its not dumb, thats how experienced scripters do,to avoid memory leaks
You shouldn’t run alot of functions consistently to maintain performance

5 Likes

This should work. (didn’t notice this was already solved due to no mark)

local Plr = game:GetService("Players").LocalPlayer
local Mouse = Plr:GetMouse()
local shootEvent

shootEvent = Mouse.Button1Down:Connect(function()
	-- do stuff
end)

local function WeaponUnequipped()
	shootEvent:Disconnect()
end

script.Parent.Unequipped:Connect(WeaponUnequipped)
3 Likes