I am trying to make a spawner that spawns zombies, but the spawner fills up the workspace with too many zombies at a time and the game gets laggy. I want the zombies to despawn once they have not been attacked for more than a minute.
Here is the code below. (The problem with this is that this despawns the zombie after 60 seconds, regardless if he has been attacked or not.)
local zombie = script.Parent.Parent wait(60) zombie:Destroy()
The Debris service has a method, AddItem()
, made specifically for what you're trying to accomplish. AddItem()
has two parameters:
The Instance to be added to Debris.
A number indicating the amount of time (in seconds) the Instance will last.
Example of using Debris:AddItem()
:
local Debris = game:GetService("Debris") local part = Instance.new("Part") part.Name = "Temporary" part.Parent = workspace Debris:AddItem(part, 5)
In the above code, part
is added to Debris and it will last 5 seconds before being removed.
the following script will delete the zombie after death or when not damaged after 60 seconds
wait() local zombie = script.Parent.Parent local humanoid = zombie:FindFirstChildOfClass("Humanoid") local healthcap = 100 local timetodelete = 60 repeat wait(1) timetodelete = timetodelete - 1 if humanoid.Health < healthcap then --reset the timer to 60 after taking damage timetodelete = 60 end healthcap = humanoid.Health --find their current health until timetodelete <= 0 or humanoid.Health <= 0 if humanoid.Health <= 0 then wait(3) --give the zombie extra time for their corpse to appear before removal end zombie:Destroy() --delete zombie after 60 seconds when left undamaged or killed