Why does creating a coroutine halt script?

Hello, I am making a tower defense game, and I am having trouble with coding a speical ability for the enemies. I have the code for the special ability in a function in a module script, and I want it to run in a coroutine to not stop the rest of the script. However, everytime I create a coroutine, the script immediately halts as if it is just running the function normally. Heres the code running it from the script:

if zombieConfigs["SpecialAbility"] then
	print("got to coroutine") -- this prints
	speicalAbility = coroutine.create(zombieConfigs.SpecialAbility()) -- I'm not even sure if this runs
	print("got past coroutine") -- this does not print
end

if speicalAbility ~= nil then
	coroutine.resume(speicalAbility)
end

Heres the function in the module script:

function module.SpecialAbility()
	local publicFunctions = require(game.ReplicatedStorage:FindFirstChild("PublicFunctions"))
	while wait(15) do
		script.Parent.Humanoid:LoadAnimation(script.Summon):Play()
		task.wait(1)
		
		script.Parent.HumanoidRootPart["1"]:Play()
		script.Parent.HumanoidRootPart["2"]:Play()
		
		for i, particle in pairs(script.Parent.HumanoidRootPart.splode:GetChildren()) do
			particle.Enabled = true
		end
		
		game:GetService("TweenService"):Create(script.Parent.HumanoidRootPart.PointLight, TweenInfo.new(0.15), {Brightness = 80}):Play()
		
		for i=1,3 do
			publicFunctions.spawnZombie("Barbarian", workspace["WORKSPACE_MAP"].Waypoints, false, CFrame.new(script.Parent.HumanoidRootPart.Position.X, workspace["WORKSPACE_MAP"].Waypoints["1"].Position.Y, script.Parent.HumanoidRootPart.Position.Z))
			task.wait(0.125)
		end
		
		script.Parent.HumanoidRootPart["3"]:Play()
		game:GetService("TweenService"):Create(script.Parent.HumanoidRootPart.PointLight, TweenInfo.new(0.15), {Brightness = 0}):Play()
		
		for i, particle in pairs(script.Parent.HumanoidRootPart.splode:GetChildren()) do
			particle.Enabled = false
		end
	end

lmk if you need more information, thank you for reading, any and all help is appreciated.

1 Like

try using task.spawn instead

1 Like

Coroutines have since become obsolete.

As this poster said, use the task library.

task.spawn will return a thread, similar to coroutines. Additionally, they are pushed to their own separate thread in runtime, just like coroutines.

These threads can easily be cancelled using task.cancel. They cannot be paused, however, so you will have to build your game using a form of debounce or state machine.

You are executing the function using () which causes the yield. Just remove the ().

2 Likes