How do I get a coroutine to completely reset for next use?

I’m writing a modular-ish NPC dialogue system where a client script analyzes a audio and depending on the audio’s playback loudness it fires an event which communicates to the server to activate a separate script which randomizes a decal on the NPC’s face, which makes the NPC look like it’s talking.

The script works fine the first time, but when I do it again (as in I trigger another NPC to use the function) it does not work and pauses, only firing the “stopped” event once. So basically it works for the 1st time, it doesn’t for the 2nd time. So how do I the coroutine to completely reset itself for the next iteration?

I am pretty new to scripting so if you could point out anything I’m doing wrong as well as dumbing it down for me, I would really appreciate it.

I’ve looked on the developer hub but I honestly could not really find that much documentation surrounding this issue. Trying to use coroutine.create hasn’t worked.

local Talk = coroutine.wrap(function(audio)	-- main function
				
	while true do
		wait(0.01)
		
		if audio.PlaybackLoudness > 1 then
			
			StartTalking:FireServer() -- open event
			print("Started")
			
		else
			
			StopTalking:FireServer() -- close event
			print("Stopped")
			
		end	
		
		if audio.PlaybackLoudness == 0 then -- Stops the audio. 
			wait()
			if audio.PlaybackLoudness == 0 then
				coroutine.yield()
			end
	end
	end
end)




GuardTrigger1.OnClientEvent:Connect(function() -- 1st iteration
	Talk(GuardAudio1)
end)

MaintenanceTrigger1.OnClientEvent:Connect(function() -- 2nd iteration
	Talk(MaintenanceAudio1)
end)

Edit:
For some reason I didn’t think abt creating module scripts, lol

I put the main function in a module script and created a new separate coroutine for each event that called the function (instead of making just one)
This helped me a lot.

1 Like

I’d recommend using the new task.spawn(), which executes code in a separate thread. It’s an improved version of the old spawn() function.

Its a common misconception that task.spawn() is a replacement for spawn(), but according to the Developers, task.defer() is the replacement of spawn()

Oh thank you for letting me know. Do you know what each function does specifically? I’m curious

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