While task.wait() not breaking

I am making a simple Tower Defense game, (I was quite bored) and I am currently making the towers shoot the zombies. The problem is that when I delete the tower, it never stops firing anyways.

function towerattack(tower)
	coroutine.resume(coroutine.create(function()
		while task.wait(info.Towers[tower.Name].FireRate) do
			if not tower then
				break
			end
		end
	end)
end

Yes, info is defined, it is a module script that is being required. No, this is not the whole script, but it should be enough to show what I am doing. I have tried checking whether it has a humanoid, or whether the tower is still there, but it never breaks the loop. I have even tried using return instead of break. Why would it not stop the loop?

When an object is destroyed, the variables referencing that object will stay referencing it, to check if it’s destroyed you can just check if the parent is nil.

In this case,

if (not tower.Parent) then
	break
end
1 Like

That worked! Thank you, I have been stressing over this for around 2 hours with no results. Never knew that it would still reference it after being destroyed.

1 Like