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.)