find nearest player

 avatar
MatsProg
lua
a year ago
566 B
0
Indexable
Never
local Players = game:GetService("Players")

local part = --Your part

local maxDistance = 10

while true do
	wait(1)
	local nearestPlayer, nearestDistance
	for _, player in pairs(Players:GetPlayers()) do
		local character = player.Character
		local distance = player:DistanceFromCharacter(part.Position)
		if not character or 
			distance > maxDistance or
			(nearestDistance and distance >= nearestDistance)
		then
			continue
		end
		nearestDistance = distance
		nearestPlayer = player
	end
	print("The nearest player is ", nearestPlayer)
end