Function returning nil

  1. Adornee a gui to nearest player torso.

  2. Function returns nil

  3. Troubleshooting different methods

	local Closest
	for _,v in pairs(game.Players:GetChildren()) do
		if v then
			local ray = Ray.new(game.Players.LocalPlayer.Character.HumanoidRootPart.Position, (v.Character.HumanoidRootPart.Position - game.Players.LocalPlayer.Character.HumanoidRootPart.Position))
			local ignore = {Player.Character}
			local hit,position,normal = game.Workspace:FindPartOnRayWithIgnoreList(ray,ignore)
			if v.Character and (v.Character.HumanoidRootPart.Position - Player.Character.HumanoidRootPart.Position).magnitude < 5 and hit == v then
					Closest = v.Character
				end
			end
		end
	return Closest
end

Try this out

local nearest

-- Main function to get the nearest player
for _, plr in pairs(game.Players:GetPlayers()) do
	local char = plr.Character or nil
	
	if char == nil then continue end
	
	local dist = char:DistanceFromCharacter(game.Players.LocalPlayer)
	
	if nearest and dist >= nearest then
		continue
	end
	
	nearest = plr
end

-- Adornee ui below vv
ui.Adornee = nearest.Character.PrimaryPart