I’m trying to run a function in another thread on a script that gets deleted but however despite that, the task.delay() still refuses to run when the script gets deleted despite spawning on a different thread, what do?
Note that task.spawn
has same issue too.
--
function Module.Stop(Character,Duration)
Character.PrimaryPart.Anchored = true
task.delay(Duration,function() -- won't run if the calling script gets deleted
Character.PrimaryPart.Anchored = false
end)
end
--
(function(...)
coroutine.wrap(Module.Stop)(...,2)
end)(Character)
task.delay(1,function()
script:Destroy()
end)
1 Like
Bump. Still looking for a solution for this, been trying every method but no luck.
I have a solution but its extremely hacky. Essentially the goal here was to start the coroutine in a script other then the one it was created in, as such it would be running in its own thread that has no direct correlation with any others.
I started out by creating a Module called AntiGc (AntiGarbageCollect) and I put this code in there
--[[ Module Script ]]--
local Antigc = {}
local bind = Instance.new("BindableEvent")
bind.Event:Connect( function(cor, ...)
coroutine.wrap(cor)(...)
end)
function Antigc.Coroutine(foo, ...)
bind:Fire(foo, ...)
end
return Antigc
When you call Antigc.Coroutine()
you put in the function that you want to turn into a coroutine and the parameters for the function following that. Essentially what does function does is that is sends the coroutine through the event system to another thread (placed conveniently in the same script) and it starts it there, making it so that if the original script gets deleted the coroutine would keep running.
Test Script:
--[[ Local Script ]]--
local antigc = require(game.ReplicatedStorage.AntiGarbageCollect)
antigc.Coroutine(function()
local count = 1
while true do
wait()
print("Test " .. count)
count += 1
end
end)
task.wait(2)
script:Destroy()
1 Like
Would this cause a bindable event to be created everytime the module is called or no?
Nope it will only be created once per machine that requires the module
1 Like