How do I get the part with the closest size to a selected part?

I want to get the part with the closest size to a selected part

I have tried to look at other posts but cant find anything that helps me
This is the code i have now, but it dont work:

local selectedPart = workspace.RedBox

local PartsFolder = workspace.PartsFolder

local parts = {
	part1 = PartsFolder.Part1,
	part2 = PartsFolder.Part2,
	part3 = PartsFolder.Part3,
}

local closestPart = nil

for i, part in parts do
	if closestPart == nil then
		closestPart = parts.part1
	else
		if selectedPart.Size.X >= part.Size.X and selectedPart.Size.Y >= part.Size.Y and selectedPart.Size.Z >= part.Size.Z then
			closestPart = part
		end
	end
end

print(closestPart.Name)

What do you mean closest size? Could you elaborate?

I want to know what part has a size that is the same or almost the same as the selected part

You could calculate the differences between the X, Y, and Z values between the original part and modified part. Then, you could identify the which is closest by identifying the part with the smallest difference.

For example, let’s say the original part is 1 by 1 by 1, and then we’ll have 3 other parts similar to that part:

  • Original Part - (1, 1, 1)
  • Part A - (1.5, 1.5, 1.5)
  • Part B - (0.25, 0.25, 0.25)
  • Part C - (5, 5, 5)

You will have to find the difference of each value by subtracting it to the original part value. Once you calculate that, you determine which one has the lowest difference, and in this case, that would be Part A, because the difference of all values are 0.5, which is the lowest compared to Part B, 0.75, and Part C, 4.

With that in mind, we can modify your script to do this. I tested this myself in studio, and it worked perfectly everytime.

local selectedPart = workspace.RedBox

local PartsFolder = workspace.PartsFolder

local parts = {
	part1 = PartsFolder.Part1,
	part2 = PartsFolder.Part2,
	part3 = PartsFolder.Part3,
}

local closestPart = nil

local partDifferences = {}

for i, part in parts do
	local differenceInX = math.abs(selectedPart.Size.X - part.Size.X)
	local differenceInY = math.abs(selectedPart.Size.Y - part.Size.Y)
	local differenceInZ = math.abs(selectedPart.Size.Z - part.Size.Z)
	local absoluteDifference = differenceInX + differenceInY + differenceInZ

	table.insert(partDifferences, {part, absoluteDifference})
end

table.sort(partDifferences, function(a, b)
	return a[2] < b[2]
end)

closestPart = partDifferences[1][1]

print(closestPart)

This worked!
Thank you so much

1 Like

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