Stopping thread on Humanoid death?

I’m trying to make boss fight, but has little bug that boss still attacks after it dies.
I could try few methods but I don’t think these are good practice.

First, I added “if” to check if it’s dead.

local function attack()
	wait(1)
	if not dead then print("attack") end
	wait(1)
	if not dead then print("attack") end
	wait(0.5)
	if not dead then print("i throw projectile") end
end

this kinda works but code looks really messy.

Second, I tried coroutine.close to stop it.

local dead = false
local currentCo = nil

coroutine.wrap(function()
	wait(1.5)
	dead = true
	print("i died")
	coroutine.close(currentCo)
end)()

local function attack()
	wait(1)
	print("attack")
	wait(1)
	print("attack")
	wait(0.5)
	print("i throw projectile")
end

currentCo = coroutine.create(function()
	attack()
end)
coroutine.resume(currentCo)

also this one works too, but it printed “cannot resume dead coroutine” at last.
And I don’t even think this is how coroutines are used for, just to stop thread.

Then, what should I use for this problem?

1 Like

To check if a humanoid dies then you can either check if Humanoid.Health is zero or tie a function to Humanoid.Died event. And rather thancoroutines. Just use normal functions. Because then you can simply kill the function via using return.
e.g.
code here
if Dead then return end
More code that will run if dead isn’t true.

Well, you can use task.spawn and task.cancel.

task.spawn will return a thread, then you use task.cancel to stop that thread from running

For example

local toCancel = task.spawn(function()
   print("Hello!")
   task.wait(5)
   print("World!")
end)

task.wait(1)
task.cancel(toCancel)

-- Only `Hello!` will be printed due to the thread being cancelled before 5 seconds passed

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