# Finding objects help

issue is im tryinng to find a certain amount of objects that are the closest to a player for example:
i want to find the closest 5 parts

sometimes returns the same object 13 times even tho there are enough parts (amount is 20 currently)

module.GetClosestScoobAmount = function(item,Amount)
local closests = {}

``````if #game.Workspace:WaitForChild("Scoobies"):GetChildren() >=  Amount then

for i = 1,Amount do
local current = nil

for i,v in pairs(game.Workspace.Scoobies:GetChildren()) do

if v:FindFirstChild("ScoobieHealth")  and v.ScoobieHealth.Value > 0 and v:FindFirstChild("Immortal") == nil  then

if current == nil then
current = v
else

if (item.PrimaryPart.Position - v.Position).Magnitude <  (item.PrimaryPart.Position - current.Position).Magnitude  then
if table.find(closests,v) == nil then
current = v
end

end

end

end

end

print(current.Position)
table.insert(closests,current)
end

else
print("not enough")
repeat
for i,v in pairs(game.Workspace.Scoobies:GetChildren()) do

if v.ScoobieHealth.Value > 0 and v:FindFirstChild("Immortal") == nil and v:FindFirstChild("ScoobieHealth") then
table.insert(closests,v)
end

end
until #closests >= Amount or #game.Workspace.Scoobies:GetChildren() == 0 or  #game.Workspace.Scoobies:GetChildren() == nil

end

if closests == nil or closests == {} then
return "Nothing"
end

return closests
``````

end

found a solution:

replace

if current == nil then
current = v
else

with

if current == nil and table.find(closests,v) == nil then
current = v
else

1 Like

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