# Deteting Nearest enemy

I need some help, I’ve been trying to make a system were it finds the nearest enemy to a tower based on a waypoint heres my code for it currently,

``````function findNearestWaypoint(pos)
local Workspacelistofitems = game.Workspace.Map.WayPoints:GetChildren()
local waypoint = nil
local dist = math.huge
local temp = nil
local temp2 = nil
for x = 1, #Workspacelistofitems do
temp2 = Workspacelistofitems[x]
if (temp2.className == "Part") and (temp2 ~= script.Parent) and game.Workspace.Map.WayPoints:FindFirstChild(tonumber(tostring(temp2)) + 1) then
temp = game.Workspace.Map.WayPoints[tonumber(tostring(temp2)) + 1]
if (temp ~= nil) then
if (temp.Position - pos).magnitude < dist then
waypoint = temp
dist = (temp.Position - pos).magnitude
end
end

elseif (temp2.className == "Part") and (temp2 ~= script.Parent) then
temp = temp2
if (temp ~= nil) then
if (temp.Position - pos).magnitude < dist then
waypoint = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return waypoint
end

function findNearestTorso(pos)
local Workspacelistofitems = game.Workspace.Zombies:GetChildren()
local torso = nil
local temp = nil
local dist = script.Parent.StatsFolder.Range.Value
local human = nil
local temp2 = nil
for x = 1, #Workspacelistofitems do
temp2 = Workspacelistofitems[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - script.Parent.HumanoidRootPart.Position).magnitude < dist then
print(math.floor(dist + 0.5).." "..x.." "..math.floor((temp.Position - script.Parent.HumanoidRootPart.Position).magnitude + 0.5))
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end