How can I make a tower shoot the first enemy?


So I’m making a game similar to Bloons TD 5 or Tower Defense on ROBLOX. I have a wave script which spawns enemies each round, and I’ve run into an issue; The towers don’t shoot the first npc, instead they shoot the closest one and I don’t know how to fix this. :confused:

Here is my code:

local turn = script.Parent.Turn

local stats = script.Parent.Statistics
local damage = stats.Damage
local range = stats.Range
local fireRate = stats.FireRate

while wait(fireRate.Value) do
	local target = nil
	for i,v in pairs(workspace.TestMap:GetChildren()) do
		local human = v:FindFirstChild("Humanoid")
		local torso = v:FindFirstChild("Torso")
		if human and torso and human.Health > 0 then
			if (torso.Position - turn.Hit.Position).magnitude <= range.Value then
				target = torso
	if target then
		turn:SetPrimaryPartCFrame(, target.Position))
		local beam ="Part")
		beam.BrickColor ="Bright red")
		beam.FormFactor = "Custom"
		beam.Material = "Neon"
		beam.Transparency = 0.25
		beam.Anchored = false
		beam.Locked = true
		beam.CanCollide = false
		local distance = (target.Position - turn.Hit.Position).magnitude
		beam.Size =, 0.5, 2)
		beam.Parent = script.Parent
		beam.CFrame =, target.Position) *, 0, -distance / 2)
		beam.Velocity = beam.CFrame.lookVector * 250
		local db = false
			if hit.Parent:FindFirstChild("Humanoid") and hit.Parent == target.Parent and db == false then
				db = true
				hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - damage.Value
				game:GetService("Debris"):AddItem(beam, 0.01)
		game:GetService("Debris"):AddItem(beam, 2)


Any help is appreciated!


1 Like

To fix this, transfer the wave data to the turret script (maybe use bindable events or module scripts), then order the turrets targets by the table. You can also check for range and iterate through the list then.

1 Like