find nearest player

 avatar
MatsProg
lua
2 years ago
566 B
3
Indexable
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
Editor is loading...