Help with my tower attack script

  1. What do you want to achieve?
    Successfully making an attack script that attacks the closest enemy inside a specific range

  2. What is the issue?
    So I am making an attack script for towers ( like the ones in tower defense games ). It does give me the closest enemy from the tower ( I tested it with print and it does work ). However when it comes to attacking, it gets buggy and sometimes show "attempting to index nil with TakeDamage().
    ( the screenshots and descriptions are below I had to follow this template )

  3. What solutions have you tried so far?
    I already asked for help on sensing humanoid in a specific range and sensing it leaving a specific range ( I was told to make a table full of enemies inside the range, and check everytime before attacking if the enemy is still inside the range, and this is the part when it gets buggy )

here is the code that gets the closest enemy inside the specific range:

function findClosestEnemy()
	for i, v in ipairs(game.Workspace.Enemies:GetChildren()) do
		if v then
			local enemyHumanoid = v:FindFirstChild("HumanoidRootPart")

			if enemyHumanoid then
				if (enemyHumanoid.Position - towerHumanoidRoot.Position).Magnitude < radius.Value then
					table.insert(enemiesInsideRadius, v)
					local distance = (enemyHumanoid.Position - towerHumanoidRoot.Position).Magnitude
					if distance < nearestDistance then
						nearestDistance = distance
						closest = v
					end
				end
				
			end
			
			
		end
	
	end
	return closest
end

( this part works perfectly )
here is the code where it attacks the enemy “closest”:

while true do 
	targetted = findClosestEnemy()
	if targetted ~= nil  then
		
		for i, v in pairs(enemiesInsideRadius) do
			if v == targetted then
				shoot(targetted)
			else
				print("Enemy left range")
			end
		end
	else
		print("Nothing is targetted")
	end
	task.wait(2)
end

( enemiesInsideRadius is the table full of enemies that are inside the specific radius )

Somehow, the tower works at first, attacking the closest enemy every 2 seconds. But once it starts to print “Enemy left range”, the tower bugs and stops attacking even though it keeps printing this:


Oh yes, and it also shows “Nothing is targetted” when I placed the tower and enemies are not spawned yet, so that part works.
I really need help as I am stuck here for like a week already… thanks.

Hi
Maybe try to put break after print(enemy left) statement . I haven’t try this yet cuz im on phone

No it doesn’t work, now it just breaks the whole loop and stops the whole thing

nevermind solved! It was because too many enemies were spawning and it lags the whole game ( I think ), now it works

1 Like