Trying to make a Gun turrent look towards the nearest target but having issue

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


The reason you’re going out of bounds on your table is because of you’re looping through every element in your table, and each iteration accessing the next index. On your final element in the table, you’re reaching for an index one beyond the size of your table, which is where you’re erroring.

Also, looping through every single possible target twice is not very efficient when you could loop through the table once like so:

local minDistance = MAX_NUMBER -- the range of your turret
local closestTarget = nil
for i, target in pairs(posibleTargets) do
	local distance = (barrel.Position - target.Position).Magnitude
	if distance < minDistance then
		minDistance = distance
		closestTarget = target
	end
end
if closestTarget then
	print("Found a target in range!")
end
1 Like