Here is some efficiency overkill since we know how taxing a lot of npc's can be.
local getTorsos;
do
local descendants = game.Workspace:GetDescendants()
local allTorsos = {}
for x = 1, #descendants, 1 do
if (descendants[x].Name == "Torso") then
allTorsos[#allTorsos + 1] = descendants[x];
end
end
game.Workspace.DescendantAdded:connect(function(descendant)
if (descendant.Name == "Torso") then
allTorsos[#allTorsos + 1] = descendant; print(#allTorsos)
end
end)
function getTorsos(position, ignore)
local output = {}
local cleanup = {}
local ignore = (ignore or {})
for x = 1, #allTorsos, 1 do
local torso = allTorsos[x]
if (torso.Parent == nil) then
cleanup[#cleanup + 1] = x
elseif (not ignore[torso]) then
output[#output + 1] = {torso; (torso.Position - position).magnitude;};
end
end
for x = #cleanup, 1, -1 do
table.remove(allTorsos, cleanup[x])
end
table.sort(output, function(torso0, torso1)
return (torso0[2] < torso1[2]);
end)
return (output)
end
end
while true do
wait(1) --[[I don't suggest you actually do it this fast if you don't need to but this is just for the example.]]
local torsos = getTorsos(Vector3.new(0, 10, 0), { --[[This Vector3 can be replaced with game.Workspace.npc.Torso.Position]]
[game.Workspace.npc.Torso] = true; --[[Example of how to not include itself, since it will always be closest to itself.]]
})
if (#torsos > 0) then --[[Make sure it found something.]]
print("________")
local nearestTorso = torsos[1][1] --[[Example of how to get the closest torso from the list.]]
local nearestTorsoDistance = torsos[1][2] --[[Example of how to get the closest torsos distance.]]
for x = 1, #torsos, 1 do
print(torsos[x][1].Parent.Name)
end --[[Example of how to print all the torsos characters names in order of distance. (Closests first.)]]
end
end |