Cannot resume dead coroutine (coroutine.wrap)

I have this LocalScript that loops through all the NPCs in the game, and if you trigger the ProximityPrompt in the NPCs then it will run a function. I used a coroutine.wrap for the function since there’s a lot of waits, and I don’t want it to mess up the other ProximityPrompts. Here is my code:

for _,v in pairs(npcs:GetChildren()) do
	if v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("HumanoidRootPart"):FindFirstChild("ProximityPrompt") then
		if v.Name == "QuestNPC2" then
			v.HumanoidRootPart.ProximityPrompt.Triggered:Connect(coroutine.wrap(ryanTriggered))
		end
	end
end

It works perfectly fine the first time but if you trigger the ProximityPrompt again it says “cannot resume dead coroutine”, and I have no idea what to do.

Also pretend there’s more if statements running different functions, the reason there’s only one is because it’s incomplete, once it’s finished there will be an if statement for each NPC. So don’t say ‘Don’t use a loop because you can just do npcs.QuestNPC2.HumanoidRootPart.ProximityPrompt.Triggered’.

Try

for _,v in pairs(npcs:GetChildren()) do
	if v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("HumanoidRootPart"):FindFirstChild("ProximityPrompt") then
		if v.Name == "QuestNPC2" then
			v.HumanoidRootPart.ProximityPrompt.Triggered:Connect(function(...))
				task.spawn(function()
					ryanTriggered(...)
				end)
			end)
		end
	end
end

oh yeah I forgot connections make a new thread already just do

for _,v in pairs(npcs:GetChildren()) do
	if v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("HumanoidRootPart"):FindFirstChild("ProximityPrompt") then
		if v.Name == "QuestNPC2" then
			v.HumanoidRootPart.ProximityPrompt.Triggered:Connect(ryanTriggered)
		end
	end
end

my bad

Is there a reason you’re trying to create a thread inside of a connection? When an event fires a new thread is created with whatever function is passed to it so I don’t think it’s necessary here.

.Triggered:Connect(coroutine.wrap(callback)) makes one coroutine for Triggered to call. When it happens a second time, it will try to resume the existing coroutine, which will fail.

local coPrint = coroutine.wrap(print)
coPrint("hooray")
coPrint("oh no!") -- will error

Events that yield will not block anything. You don’t need anything here other than :Connect(ryanTriggered).

3 Likes

You do not need to use coroutine.wrap, events will already split off into coroutines/threads on their own.

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