I am trying to get the target but the script keeps on saying that I am getting nil for my distances table. It is a bit hard to explain but here is my script and some screenshots.
local barrel = script.Parent
local bulletSpeed = 200
local damage = 1
local fireRate = 0.1
local range = 50
local bullet = game.ReplicatedStorage.Bullet
while wait(fireRate) do
local posibleTargets = {}
local target = nil
local distances = {}
for i , v in pairs(game.Workspace:GetChildren()) do
if v:FindFirstChild("Humanoid") and (v:FindFirstChild("Torso").Position - barrel.Position).Magnitude < range then
posibleTargets[i] = v.Torso
end
for i , distance in pairs(posibleTargets) do
distances[i] = (barrel.Position - distance.Position).Magnitude
end
table.sort(distances)
for i,v in pairs(posibleTargets) do
if (v.Position - barrel.Position).Magnitude >= distances[0+i] and (v.Position - barrel.Position).Magnitude < distances[1+i] then
target = v
end
end
end
--TARGET HAS BEEN FOUND!!
barrel.CFrame = CFrame.new(barrel.Position,target.Position)
end

