RunService.Heartbeat not disconnecting correctly

Goal: It begins an attack, you have 2 soldiers, each soldier is picked which than fires the “lookForEnemy” function. In there, it picks a random enemy and checks the distance from the enemy and your own soldier, if too far, it picks another random one until it finds one that’s close to attack.

Problem: Once the first soldier is close enough, it works fines. But when the second soldiers get close enough, the disconnect doesn’t seem to work.

I believe this has to do with the for loop where it calls the “lookForEnemy” function on the bottom.

https://gyazo.com/a3fc8de56fbea75772d3774c22011285

Code that I use:

RunService = game:GetService("RunService")
local ais = game.Workspace.ais:GetChildren()

local function attack()
	print("ATTACk")
end

local function lookForEnemy(v)
	Connection = RunService.Heartbeat:Connect(function()
		print("looking")
		local pickedEnemy = ais[math.random(1, #ais)]
		if pickedEnemy.Owner.Value ~= "-1" then
			local enemyPos = pickedEnemy.Position
			local myPos = v.Position
			local distance = (enemyPos - myPos).magnitude
			if distance <= 10 then
				attack()
				Connection:Disconnect() 
			end
		end
		wait(.1)
	end)
end

for i,v in pairs(game.Workspace.ais:GetChildren()) do
    if v.Owner.Value == "-1" then
		print("test")
        lookForEnemy(v)
    end
end

This appears to be an issue with how you’re defining the “Connection” variable. Currently, you’re defining it as a global variable, meaning it can be accessed by any part of the script.

Because of this, only one of soldiers’ events will disconnect, because each new soldier will overwrite the connection of the previous one.

This should be fixed by changing the way you define it from Connection = ... to local Connection = .... This will change it to a local variable, meaning the definition is unique to each call of the “lookForEnemy” function.

1 Like

Okay, so I did that, however when I change it to a local variable then it says Connection is an unknown global variable.
image

Hmm, that’s odd. I assume that’s because you’re trying to access the variable from within the declaration of the variable. The script will probably still work, even with that warning.

The easiest way to silence this warning (to my knowledge) is to add a blank local Connection on the line before you initially define “Connection”, like this:

local function lookForEnemy(v)
	local Connection
	Connection = RunService.Heartbeat:Connect(function()
5 Likes