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.
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.
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
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)