Finding closest object to a player

hey! I’m currently trying to find out how to find an object closest to a player, through its name. any help would be appreciated, thank uu!

2 Likes
local objectFolder = workspace.Folder

local players = game:GetService("Players")
local player = players.LocalPlayer

local function getClosestObject()
	local closestDistance, closestObject = math.huge, nil
	for _, object in ipairs(objectFolder:GetChildren()) do
		if object:IsA("BasePart") then
			local distance = player:DistanceFromCharacter(object.Position)
			if distance < closestDistance then
				closestDistance = distance
				closestObject = object
			end
		end
	end
	return closestObject
end

local closestObject = getClosestObject()

This should help give you a rough idea.

1 Like

Question. what do these lines do and is it needed and where do I put my code to do things with the nearestt object

1 Like

They keep track of the closest distance and the closest object while the folder of instances is being iterated over.

1 Like

ah alright. where would I put my code to do things with the nearest object

1 Like