Cannot resume dead coroutine

  1. What do you want to achieve?

I want to clear the error being produced “cannot resume dead coroutine”

  1. What is the issue?

I’m not able to find where or what is causing this error to produce. This seems to occur right after when the reload time finishes.

  1. What solutions have you tried so far?

What I have attempted to do is to create a boolean for the thread running and cancel it when I unequipped my weapon. I have also tried to cancel tween in my function below, but it doesn’t seem to remove that message. I believe some thread is still running after I have canceled the thread.

Also if you like, let me know what I can do to improve upon what I have written in my code :slight_smile:

-- module script
function gunMechanic.reload(localPlayer, weapon)
	if Bullet_is_not_same and Is_not_reloading then
		local gunMechanic = require(ReplicationStorage.gunMechanic) -- visual cooldown GUI using tween, no wait/delay
		weapon.reload = true
		local cooldownTween = gunMechanic.cooldown(localPlayer, weapon, weapon.configuration.stat.RELOAD_TIME.Value)
		local threadRunning = true
		
		local delayThread = coroutine.create(function()
			print("reloading...")
			wait(weapon.reload_time)
			print("reloaded")
			threadRunning = false
			BULLET_IN_CLIP.Value = AMMO_CAPACITY.Value
			weapon.reload = false
		end)
		
		task.spawn(delayThread)
		
		while weapon.reload.Value == true and weapon.equipped.Value == true do
			task.wait() -- ends thread when unequipped or finish reloading
		end

		print("reload finish or interrupted")
		if threadRunning == true then
			cooldownTween:Cancel()
			task.cancel(delayThread)
		end
	end
end

I have found some new information regarding to this problem. Apparently in “delayThread”, the function is still running even though I have canceled the thread. I have tested with a for loop and found that the thread is still running. Was I suppose to cancel the thread with task.cancel?

local delayThread = coroutine.create(function()
			print("reloading...")
			for i = 1, weapon.configuration.stat.RELOAD_TIME.Value do -- this loop was still running
				wait(1)
				print("waiting...")
			end
			print("reloaded")
			threadRunning = false
			weapon.configuration.current.BULLET_IN_CLIP.Value = weapon.configuration.fun.AMMO_CAPACITY.Value
			weapon.configuration.current.IS_RELOAD.Value = false
		end)

why don’t you just do this:

task.spawn(function()
	print("reloading...")
	wait(weapon.reload_time)
	print("reloaded")
	threadRunning = false
	BULLET_IN_CLIP.Value = AMMO_CAPACITY.Value
	weapon.reload = false
end)
1 Like

I wanted to create a function to cancel that current thread, hence I made coroutine to cancel it with task.cancel when the player unequips their tool. If you look at the original post, I created a function in which the player will stop reloading the moment they unequipped or finished reloading, which does work, but the error “Cannot resume dead coroutine” is printed in the output.