Hello there travelers!
I am currently working on a weapon system, however I came across a road block:
I am trying to halt the player from continuing to reload if they put away their weapon and I was tracking when the parent of the tool changes. Although I tried to close the thread through task.cancel, it stills runs even after 3 seconds as it prints out “Returned because player didn’t wait” when the reloading is done and the tool is re-equipped. Here is a snippet of the code.
Oh and if there is a way to stop the thread instantly when the parent of the tool changes that would be great.
if CurrentWeaponMag.Value == 0 then
local MagFill = true
print("Mag empty, sent reload")
WeaponaryEvent.Value:FireClient(FiredPlayer, "RELOAD")
local Thread = task.defer(function()
Dart:GetPropertyChangedSignal("Parent"):Connect(function()
if MagFill == true then
print("Returned Because Player Didn't Wait")
MagFill = false
CoolDown.Value = false
return MagFill
end
end)
end)
task.wait(3)
task.cancel(Thread)
if MagFill == true then
CurrentWeaponMag.Value = WeaponMagMax
print("Mag Refilled")
end
CoolDown.Value = false
elseif CurrentWeaponMag.Value > 0 then
print("Mag is ready")
task.wait(FireRate)
CoolDown.Value = false
end
You’re creating a connection to a signal without disconnecting it. It does not matter that the thread you created the connection in has been cancelled; the connection will still remain in memory until you disconnect it.
Do this instead:
if CurrentWeaponMag.Value == 0 then
local MagFill = true
print("Mag empty, sent reload")
WeaponaryEvent.Value:FireClient(FiredPlayer, "RELOAD")
local connection = Dart:GetPropertyChangedSignal("Parent"):Connect(function()
if MagFill == true then
print("Returned Because Player Didn't Wait")
MagFill = false
CoolDown.Value = false
return MagFill -- edit: this doesn’t do anything; you can remove it
end
end)
task.wait(3)
connection:Disconnect()
if MagFill == true then
CurrentWeaponMag.Value = WeaponMagMax
print("Mag Refilled")
end
CoolDown.Value = false
elseif CurrentWeaponMag.Value > 0 then
print("Mag is ready")
task.wait(FireRate)
CoolDown.Value = false
end
Thank you this worked right! I learned something new. Btw, I know return MagFilled doesn’t do anything, just had it there because why not. Do you know a way to end the connection as soon as Magfill becomes false?
Then you disconnect the connection wherever you set MagFill to false. If you want to disconnect it when the tool’s parent changes, you can do this:
local connection
connection = Dart:GetPropertyChangedSignal("Parent"):Connect(function()
connection:Disconnect()
if MagFill == true then
print("Returned Because Player Didn't Wait")
MagFill = false
CoolDown.Value = false
end
end)