It feels like this is the easiest task that LUA could do, but somewhy I just cannot figure it out. I believe the easiest way would be listing the found HumanoidRootParts magnitudes in an array, then using math.min() to find the least argument. But how to create this array? Or is there a simpler way?
This is what I have; Searches through workspaces models, finding HumanoidRootParts, then calculating the magnitudes between player and found HumanoidRootParts. How to make the code find out which of the parts is closest?
descendants = game.Workspace:GetDescendants()
for index, descendant in pairs(descendants) do
if descendant.ClassName == "Model"
then
local keppi = descendant:FindFirstChild("HumanoidRootPart")
if keppi then
local magnitude = (player.Character.HumanoidRootPart.Position - keppi.Position).magnitude
if magnitude <= 20 and magnitude >= 1 then
print(keppi.Parent.Name.." is close as heck")
foundtarget = keppi
end
end
end
end
Thanks in advance!
Solution:
--foundtarget = player.Character.Head
--local bestmagn = 20
local descendants = game.Workspace:GetDescendants()
for index, descendant in pairs(descendants) do
if descendant.ClassName == "Model"
then
local keppi = descendant:FindFirstChild("HumanoidRootPart")
if keppi then
local magnitude = (player.Character.HumanoidRootPart.Position - keppi.Position).magnitude
if magnitude <= 20 and magnitude >= 1 then
print(keppi.Parent.Name.." is close as heck")
--if magnitude <= bestmagn then
--print("better solution found")
--bestmagn = magnitude
--foundtarget = keppi
end
end
end
end
end
Added parts commented in above script. With the help of TheeDeathCaster and Cabbler, I added a value that changes if any of the nearby parts are closer than the required 20, in the meanwhile it stores the best magnitudes parent to foundtarget value, which is then later used in code.

2 comments
You'd accomplish that by having a variable keep track of the distance, and a player variable to get the closest player; if that player is closer, the variable is set to that magnitude, and the player variable updates.
ok If you want to be within 20 studs you can simply edit my code "if mag<bestv then" to "if mag<bestv and mag<20 then". Because your script is still extremely inefficient if it works.