How can I find the closest part?

Now I really spent hours trying to find what I want. Basically, I have an NPC which collects Diamonds for me and I want it to collect the closest Diamond to it. To determine the closest Diamond, I have used this function:

function FindDiamond(Pose)
	repeat wait() until #Map:GetChildren() == 1
	local Lol = {}
	local Closest
	local List = Map:GetChildren()[1]:WaitForChild("Economy"):GetChildren()
	local Distance = 500
	local Template = nil
	for x = 1, #List do
		Template = List[x]
		if Template.Name == "Diamond1" or Template.Name == "Diamond2" or Template.Name == "Diamond3" then
			if (Template.Position - Pose).magnitude < Distance and Template.Position.Y <= Character:WaitForChild("Head").Position.Y then
				table.insert(Lol, Template)
				for i,v in pairs(Lol) do
					if Closest then
				    	if (v.Position - Pose).Magnitude < (Closest.Position - Pose).Magnitude then 
				        	Closest = v
				    	end
					else
				    	Closest = v
					end
				end
				return Closest
			end
		end
	end
end

It didn’t really work… It still tries collecting Diamonds so far away from it while there are ones really close to it. How do I fix?

(Diamond1, Diamond2 and Diamond3 are all Diamonds but the numbers in their name determine their rarity. It has nothing to do with the code.)

2 Likes

You’ve already got a loop running (x=1,#List), but you put a loop inside of that. The first time the original loop finds a diamond, it returns that because that Diamond will be the only object in your table “Lol”.

Try this instead:

function FindDiamond(Pose)
	repeat wait() until #Map:GetChildren() == 1
	local Closest
	local Distance = 500
	for _,Template in pairs(Map:GetChildren()[1]:WaitForChild("Economy"):GetChildren()) do
		if Template.Name == "Diamond1" or Template.Name == "Diamond2" or Template.Name == "Diamond3" then
			if Template.Position.Y <= Character:WaitForChild("Head").Position.Y then --Not sure why you want this, but I won't judge :)
				local newDistance = (Template.Position - Pose).magnitude
				if newDistance < Distance then
					Closest = Template
					Distance = newDistance -- This will cause the script to pass over any diamonds that are further than the current "closest" diamond
				end
			end
		end
	end
	return Closest
end
8 Likes

Oh god, no idea how I missed that! Thank you so much!