How do i find the closest part to a player

So For about 3 hours i have been trying to make a system that Checks an entire folder and finds the part that is closest to you within that folder.

As you can see in the script below i have tried to make a Distance and a LowestDistance and update it and add the “Closest” part to a table. This doesnt not work tho

I have given up myself trying todo this and would really be grateful if anyone out there could help me fix this.

The folder: Contains all the spawn areas of my AI. And what im trying to do is check what SpawnPart is closest to the player and spawn the AI there.

	local LowestDistance = 999999
	local Distance
	local HighestSpawnPart = {"Trail"}
	
	for i, v in pairs(workspace.Spawns:GetChildren()) do
		
		if v then
			Distance = (player.Character.HumanoidRootPart.Position - v.Position).Magnitude
			
			if Distance <  LowestDistance then
				LowestDistance = Distance
				table.remove(HighestSpawnPart, 1)
				
				table.insert(HighestSpawnPart, 1, v)
			end
			
		end
	end
	
	wait(.1)
	
	print(HighestSpawnPart)

Dont focus in this code its just an example of what ive tried todo.

local function getNearest(hrp, folder)
local parts = folder:GetChildren()
local minPart = parts[1]

for _, part in pairs(parts) do
    if (minPart.Position - hrp.Position).Magnitude > (part.Position - hrp.Position).Magnitude then
        minPart = part
    end
end
return minPart
end

print(getNearest(player.Character.HumanoidRootPart, game.Workspace.Spawns):GetFullName())

Sorry for bad indentation I’m on mobile. I’m hoping the code is self explanatory, but feel free to ask if your confused about a part of it.

1 Like

I understand it pretty well but something I don’t understand is that it’s going pretty slow. Like it does maybe 5 Spawns a second.

It shouldn’t be slow. Depending on hardware you should be able to do tens of thousands of checks per second. (Not calling the code that many times, but handle that many spawns)

It could be strange implementation from another part of your code.

Also printing is slow. So if you are printing every step you can heavily slow down its speed. But that shouldn’t effect to the point of 5 spawns per second.

Could it be because I have a Repeat loop in the same code?

Gtg. rq will be back later. Thank you for helping

It is a bit unclear to me what part of the code is running slow. Do you mean the function is only getting called 5x per second?

No it only prints the “Print” like 5 times a second

Hmm… it sounds likely that you have this in a loop that has a yield or some other heavily processing intensive code. The exact cause of the loop delay would not be from the code I supplied.

Also repeat loops are fine. The issue with loops is when they are running too much code or too many times without yielding or terminating.