It worked perfectly like this:
while wait() do local distances = {} local charwithdistance = {} for number,char in pairs (game.Workspace.NPCs:GetChildren()) do local distance = (char.Head.Position - script.Parent.Head.Position).magnitude distances[number] = distance charwithdistance[distance] = char end table.sort(distances) for number2, plr in pairs (distances) do local closestdistance = distances[(number2 + 1)] local closestplayer = charwithdistance[(closestdistance)] script.Parent.Humanoid:MoveTo(closestplayer.Head.Position) end end
But I also didn't want it to kill AIs on its team so then I did this:
while wait() do local distances = {} local charwithdistance = {} for number,char in pairs (game.Workspace.NPCs:GetChildren()) do local distance = (char.Head.Position - script.Parent.Head.Position).magnitude distances[number] = distance charwithdistance[distance] = char end table.sort(distances) for number2, plr in pairs (distances) do local closestdistance = plr local closestplayer = charwithdistance[(closestdistance)] if not closestplayer.Owner.Value == script.Parent.Owner.Value then script.Parent.Humanoid:MoveTo(closestplayer.Head.Position) return end end end
But now it doesn't work and the AI doesn't do anything, idk how to fix this, and the output says: 07:41:40.962 - Workspace.NPCs.AI.Ai Script:14: attempt to index local 'closestplayer' (a nil value) 07:41:40.963 - Stack Begin 07:41:40.964 - Script 'Workspace.NPCs.AI.Ai Script', Line 14 07:41:40.965 - Stack End