The Npc does not find the nearest object

Hello. I wrote a script in which the npc searches for the nearest object from the folder and ran to it. I used simplePath but it throws an error when I write BPath:Run(i).

local distanceTable = {}

local function distances()
for i, v in pairs(workspace.Objects:GetChildren()) do
local distanceFromPart = (BRootPart.Position - v.Position).magnitude
distanceTable[v.Name] = distanceFromPart
end

table.sort(distanceTable, function(ele1, ele2)
	return ele1[2] > ele2[2]
end)

for i, v in pairs(distanceTable) do
	print("Your distance from part "..i.." is "..v..".")
	BPath:Run(i)
end

end

Here is the function

why “i” instead of “v”???
i is an index (number) and v is the actual object you stored

distanceTable has the format of

{
    Name1 = distance1,
    Name2 = distance2,
    -- ...
}

table.sort is expecting an array of the format

{
    [1] = value1,
    [2] = value2,
    -- ...
}

Also, in your sorting function, you’re trying to index the second element of what probably is a number?

I think in this case, i might be referring to the part name and v is referring to the distance value.

How can I fix this? I’m just a beginner developer so it would be great if you could explain

Change

distanceTable[v.Name] = distanceFromPart

to

table.insert(distanceTable, {
    part = v,
    distance = distanceFromPart
})

and change

table.sort(distanceTable, function(ele1, ele2)
    return ele1[2] > ele2[2]
end)

to

table.sort(distanceTable, function(ele1, ele2)
	return ele1.distance < ele2.distance
end)

I’ve never used SimplePath but looking at the documentation, it looks like Run expects a Part and not a string(?) that you’re currently giving it. I’d get rid of that final for loop and just have something like

BPath:Run(distanceTable[1].part)

Thanks! It’s working. I will leave the full script if someone needs it.

local distanceTable = {}

local function distances()
for i, v in pairs(workspace.Objects:GetChildren()) do
local distanceFromPart = (BRootPart.Position - v.Position).magnitude
distanceTable[v.Name] = distanceFromPart
table.insert(distanceTable, {
part = v,
distance = distanceFromPart
})
end

table.sort(distanceTable, function(ele1, ele2)
	return ele1.distance < ele2.distance
end)

BPath:Run(distanceTable[1].part)

end

1 Like

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