How would I find a nearest rig from an NPC

Hi. I am making an NPC, and I want to find the CLOSEST rig possible from the NPC, and I have some code that used to work but now doesn’t. Here it is:

local function FindNearestPlayer()

    local nearPlr, near

    for index, target in pairs(workspace:GetChildren()) do
        if target:FindFirstChild("Humanoid") and target.Humanoid.Health > 0 and target.PrimaryPart  and target ~= script.Parent then
            if nearPlr and near then

                local temporary = (script.Parent.Torso.Position - target.PrimaryPart.Position).magnitude

                if temporary < near and temporary <= 50 then
                    nearPlr = target.PrimaryPart
                    near = temporary
                end
            else
                nearPlr = target.PrimaryPart
                near = (script.Parent.Torso.Position - target.PrimaryPart.Position).magnitude

            end
            return nearPlr
        end
    end
end

Here’s a picture:

As you can see that dummy1 is behind dummy2, but it still prints dummy1 as the closest, Help is appreciated :slight_smile:

I just fixed it. I returned nearPlr outside of the loop.

1 Like