Heartbeat not disconnecting immediately

Im making a pathfinding system for my enemies where they path randomly, it spawns a task for each enemy that uses heartbeat and for every frame in heartbeat if they cant see you nothing happens but once they do it SHOULD disconnect and stop the path and make them chase you. But for some reason calling disconnect makes the thread run 3-5 times AFTER disconnecting it. This is breaking my game and I dont know how to stop it.

task.spawn(function()
			local connection
			local running = true
			
			connection = RunService.Heartbeat:Connect(function()
				task.wait(0.5)
				print(canSeePlayer)
				if canSeePlayer and running then
					
					Path:Stop()
					Path:Destroy()
					print("path stopped") --prints like 3-5 times after disconnecting
					
					connection:Disconnect()
					connection = nil
					running = false
					
					--pathStoppedBindable:Fire()
					chasePlayer(enemy)
					
					return
				end
			end)
		end)

I added the running variable and a task.wait but that didnt stop it either.

1 Like

Any reason not to do a while task.wait() do? Though to solve your issue id just have it disconnect as fast as possible, remove the wait, and as soon as the if statement passes, disconnect. I’m guessing something in between there is taking 5 frames to run.

I did a while loop and I thought it fixed it at first but it still prints pathstopped multiple times and calls chasePlayer() multiple times aswell

task.spawn(function()
			local running = true
			
			while running do
				task.wait(0.5)
				print(canSeePlayer)
				if canSeePlayer and running then

					Path:Stop()
					Path:Destroy()
					print("path stopped") --prints like 3-5 times after running becomes false

					running = false
					--pathStoppedBindable:Fire()
					chasePlayer(enemy)

					return
				end
			end	
		end)

so that would mean that task.spawn is being ran multiple times, which probably means your original script was fine. The issue I don’t think is in this snippet of code.

You could remove the running variable and set it to while task.wait(0.5) do

in the if statement that decides whether the path should stop, you can just use break instead of running = false and return.

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