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