Is it possible to get a Coroutine to close itself when it finishes running?

  1. What do you want to achieve? Keep it simple and clear!
    I’m trying to set up a simple system that will spawn a brick visualizing a hitbox for my hitbox module. I’ve done this using a Coroutine so it can run alongside the rest of the script without yielding it.

  2. What is the issue? Include screenshots / videos if possible!
    I need the coroutine to close after it finishes running, as leaving an indefinite amount open supposedly causes memory leaks.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I tried getting the coroutine to close itself, however that simply produced an error. I couldn’t find any information describing how to pull this off.

I could theoretically wait for the coroutine to finish and close it with coroutine.close(), however if I need to yield the entire thread it defeats the point of creating a coroutine in the first place.

Code sample:

local HitboxVisualizer = coroutine.create(function()
	local part = Instance.new("Part")
	part.Anchored = true
	part.CanCollide = false
	part.CanQuery = false
	part.Parent = workspace
	part.CFrame = cframe
	part.Size = size
	part.Color = Color3.fromRGB(200, 0, 0)
	part.Material = Enum.Material.ForceField
	
	wait(2)
	
	part:Destroy()
	
	coroutine.close(HitboxVisualizer) -- causes an error. I need some way to close the coroutine when it reaches the end without yielding the main script.
end)

coroutine.resume(HitboxVisualizer) -- begins the coroutine

1 Like

If you use task.spawn or task.defer you don’t have to worry about memory leaks and its easier. You can set it up like this:

local HitboxVisualizer = task.spawn(function()
	local part = Instance.new("Part")
	part.Anchored = true
	part.CanCollide = false
	part.CanQuery = false
	part.Parent = workspace
	part.CFrame = cframe
	part.Size = size
	part.Color = Color3.fromRGB(200, 0, 0)
	part.Material = Enum.Material.ForceField

	wait(2)

	part:Destroy()
end)

But if you really wanna use coroutines you have to find a more hackier way, i could help with that if thats what you want

1 Like

This is exactly what I needed, thanks

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.