Hello, the function that gets the nearest player’s HRP returns nil.
function GetNearestPlayer()
local test = game.Workspace:GetChildren()
local max_dist = 50
local target = nil
for _,v in pairs(test) do
if v:IsA("Model") and game.Players:FindFirstChild(v) then
local test_hrp = v:FindFirstChild("HumanoidRootPart")
if (hrp.Position - test_hrp.Position).magnitude < max_dist then
target = test_hrp
end
end
end
print(target)
return target
end
Here is a quick little function I just wrote up to find the nearest player to a supplied Vector3 position.
local function getnearestplayer(position)
assert(typeof(position) == "Vector3","Position must be a Vector3!")
--
local nearestplayer = nil
local nearestdistance = math.huge
--
for i,v in pairs(game.Players:GetPlayers()) do
if v.Character then
if v.Character:FindFirstChild("HumanoidRootPart") then
local position = (v.Character.HumanoidRootPart.Position - position).Magnitude
if position < nearestdistance then
nearestdistance = position
nearestplayer = v
end
end
end
end
--
return nearestplayer,nearestdistance
end
--> Use:
---> getnearestplayer(Vector3)
This gives me an error “Argument 2 missing or nil”. I edited your code:
local function GetNearestPlayer()
local nearestplayer = nil
local nearestdistance = math.huge
for i,v in pairs(game.Players:GetPlayers()) do
if v.Character then
if v.Character:FindFirstChild("HumanoidRootPart") then
local position = (v.Character.HumanoidRootPart.Position - hrp.Position).Magnitude
if position < nearestdistance then
nearestdistance = position
nearestplayer = v
end
end
end
end
return nearestplayer,nearestdistance
end