Problem with Tower Attack(TDS)

  1. What do you want to achieve? Keep it simple and clear!
    So, basically i need my tower shoot every enemy it see
  2. What is the issue? Include screenshots / videos if possible!
    Issue is: After killing some enemies when every enemy leaves tower shoot zone tower goes to passive mode. When new wave is starting and enemies entering tower shoot zone, tower just do nothing.

image – when enemies in tower shoot zone.

– on the next wave
3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I was making that system by the youtube idk what’s wrong

My code:

local PhysicsService = game:GetService("PhysicsService")
local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local events = ReplicatedStorage:WaitForChild("Events")
local SpawnTowerEvent = events:WaitForChild("SpawnTower")
local AnimateTowerEvent = events:WaitForChild("AnimateTower")
local tower = {}
local function FindNearestTarget(newTower)
	local MaxDistance = 50
	local nearestTarget = nil
	for i, target in ipairs(workspace.MobsFolder:GetChildren()) do
		local distance = (target.HumanoidRootPart.Position - newTower.HumanoidRootPart.Position).Magnitude
		if distance < MaxDistance then
			nearestTarget = target
			MaxDistance = distance

	return nearestTarget
function tower.Attack(newTower)
	local target = FindNearestTarget(newTower)
	if target then
		local TargetCFrame = CFrame.lookAt(newTower.HumanoidRootPart.Position, target.HumanoidRootPart.Position)
		newTower.HumanoidRootPart.BodyGyro.CFrame = TargetCFrame
		AnimateTowerEvent:FireAllClients(newTower, "Attack")

So after adding a few print i discovered when enemy leaves tower’s range and after new wave started it just stops printing distance to target and target name.

Maybe i need to call that function each time i spawn new mob? Bcz when this script was in TOWER manually not in module it was working fine

it may be because of the function at the bottom but thats just me

Function at the bottom it’s attack function -_-

ok then its the for i, thing maybe

No it’s not because this is an thing which used in loop always

Ok so a day passed, but i didn’t figure any problem in script

So basically i added some FindNearestTarget() to tower.attack to loop, but it prints me an error what HumanoidRootPart is nil when enemy despawn, and i don’t know what to do