How to get closest part in a folder of parts using table.sort

  1. What I want to achieve?

I want to get the part that is closest to the point object in a folder of other parts

  1. What is the issue?

the issue is that I’ve never used table.sort or anything remotely close to this so I don’t know how too.

local Workspace = game:GetService("Workspace")

local Point = Workspace:FindFirstChild("Point")
local AllParts = Workspace.Folder:GetChildren()

function returnRange(obj1, obj2)
	return (obj1.Position - obj2.Position).Magnitude
end

table.sort(AllParts, returnRange(Point,AllParts[1]) <= returnRange(AllParts[1], Point))

for i, v in pairs(AllParts) do
	print(v)
end

Simply change it to this:

table.sort(AllParts, function(a, b)
	return returnRange(Point, a) < returnRange(Point, b)
end)

This sorts by closest, table.sort expects a function so your script won’t work as intended.

1 Like

That worked, thank you very much.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.