How I disconnect a function

im creating an ai but i need to disconnect a function but it gaves me error!

ai script:

local Slime = script.Parent
local Humanoid = Slime.Humanoid
local Animations = Slime.Animations

local Idle = Humanoid:LoadAnimation(Animations.Idle)
local Walk = Humanoid:LoadAnimation(Animations.Walk)

local function WalkCycle()
	while true do
		if Humanoid.Health >= 1 then
			wait(math.random(3,5))
			local random = math.random(-10, 10)
			Humanoid:MoveTo(Slime.WorldPivot.Position + Vector3.new(random, 0, Humanoid))
			Idle:Stop()
			Walk:Play()
			Humanoid.MoveToFinished:Wait()
			Walk:Stop()
			Idle:Play()
		end
	end
end

function OnDied()
	Walk:Stop()
	Idle:Stop()
end

coroutine.wrap(WalkCycle())
Humanoid.Died:Connect(OnDied)

please help

Change

coroutine.wrap(WalkCycle())

into

task.spawn(WalkCycle)

Also, you need a wait inside WalkCycle when health is not >= 1. Currently, it will crash.

1 Like

i done it, it doesn’t crash so it’s ok

Have you tried setting the humanoid health below 1?

Have you tried using “:disconnect()”??

(I’ve given an example of how to use it below)

local f -- Empty variable
local x = 0

f = function() -- Setting variable to function
 while wait() do
  print("YEET")
  x += 1

  if x > 5 then
   f:Disconnect() -- Function kaboom!!
  end

 end
end)
1 Like

if i kill it it continues the last pieces of the cript

@HowledBlade it doesn’t work, it continues the last pieces of the animation

what i’ve done:

local Slime = script.Parent
local Humanoid = Slime.Humanoid
local Animations = Slime.Animations
local Walking

local Idle = Humanoid:LoadAnimation(Animations.Idle)
local Walk = Humanoid:LoadAnimation(Animations.Walk)

Walking = function()
	while true do
		if Humanoid.Health >= 1 then
			wait(math.random(3,5))
			local random = math.random(-10, 10)
			Humanoid:MoveTo(Slime.WorldPivot.Position + Vector3.new(random, 0, Humanoid))
			Idle:Stop()
			Walk:Play()
			Humanoid.MoveToFinished:Wait()
			Walk:Stop()
			Idle:Play()
		end
	end
end

function OnDied()
	Walking:Disconnect()
	Walk:Stop()
	Idle:Stop()
end

task.spawn(Walking)
Humanoid.Died:Connect(OnDied)

If the the guy died, why not delete the script, maybe useless info but u can always try.

i suggest you change “while true do” into “repeat until” instead
so that it automatically disconnects the loop if " Humanoid.Health <= 0 " is equal to true

1 Like

at the end i did it so case closed!

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