Turret won't die when it has too, how can I fix this?

Hello,

I’m making a turret for my game, where there are basically enemies you have to kill kinda like a tower defense kind of game. The enemies are trying to destroy the said turret.

But whenever I try coding my turret so that it destroys itself whenever it reaches zero health, it almost seems just ignores what I put in and keeps running, is there anything I can do to fix this?

Here is the script for my turret, this is the only script I have made so far.

local Turret = script.Parent
local Range = 50
local Health = script.Parent.Parent.Humanoid.Health
local Damage = 5

while wait() do

   for i, v in pairs(workspace.Enemys:GetChildren()) do
		local Distance = (Turret.Position - v.HumanoidRootPart.Position).magnitude
		
		if Distance < Range and v.Humanoid.Health > 0 then
			local Distance = (Turret.Position - v.HumanoidRootPart.Position).magnitude
			print("In Range")
			Turret.CFrame = CFrame.lookAt(Turret.Position, v.HumanoidRootPart.Position)
			local NewProjectile = game.ReplicatedStorage.Projectile:Clone()
			NewProjectile.Parent = workspace
			NewProjectile.CFrame = CFrame.new(Turret.Position, v.HumanoidRootPart.Position)*CFrame.new(math.random(-1,1),math.random(-1,1),-Distance/2)
			NewProjectile.Size = Vector3.new(.1,.1,Distance)
			game.Debris:AddItem(NewProjectile, wait())
			
			v.Humanoid:TakeDamage(Damage)
		else
			print("No")
		end
	end
	
	if Health == 0 then
		Turret.Parent:Destroy()
	end
end

Also this is what my model looks like.
Screenshot 2022-04-16 202902

(The script is in the Union which is also the turret)

You cannot make the health a variable.
Change the if statement at the bottom to

if script.Parent.Parent.Humanoid.Health== 0 then
	Turret.Parent:Destroy()
end

this is because the variable is not getting the updated value

You should especially consider this while scripting anything else, You can define script.Parent.Parent.Humanoid as hum or something and just make it hum.Health == 0 instead, but you can’t define the values unless they are a constant. When you define a value as a variable it remembers the actual value and doesn’t update.

You can also use an event to check if the turret died.

script.Parent.Parent.Humanoid.Died:Connect(function()
    Turret.Parent:Destroy()
end)

You should use an event because that code will error when you destroy the turret. The turret will be nil when the loop is running and will spam the console with errors. Put the event before the while loop to make sure the event is connected.

1 Like