I have a master script for AI handling and I'm trying to implement a basic MoveTo function for all tagged humanoids but it only seems to apply for the first humanoid it finds. I'm not very familiar with collection service so any help is appreciated.
local CollectionService = game:GetService("CollectionService")
local ATTACK_DIST = 1000
for _,zombie in pairs(CollectionService:GetTagged("ZombieHum")) do
function findPlayerNearestTo(nearestTo)
local nearestChar, nearestHum, nearestDist
for _, p in pairs(game.Players:GetPlayers()) do
if p.Character then
local hm = p.Character:FindFirstChild("Humanoid")
if hm and hm.Health > 0 then
local d = (nearestTo - hm.RootPart.Position).magnitude
if d <= ATTACK_DIST then
if nearestDist == nil or d < nearestDist then
nearestChar = p.Character
nearestHum = hm
nearestDist = d
end
end
end
end
end
return nearestChar, nearestHum, nearestDist
end
local moving = false
while true do
local target, tHum, tDist = findPlayerNearestTo(zombie.Parent.HumanoidRootPart.Position)
if target then
zombie:MoveTo(tHum.RootPart.Position, tHum.RootPart)
moving = true
wait(0.1)
else
if moving then
zombie:MoveTo(zombie.Parent.HumanoidRootPart.Position)
moving = false
end
wait(0.5)
end
end
end
