Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to make an NPC despawn after a certain amount of time?

Asked by
2ndwann 131
5 years ago
Edited 5 years ago

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()

2 answers

Log in to vote
2
Answered by 5 years ago

Use the Debris service.

The Debris service has a method, AddItem(), made specifically for what you're trying to accomplish. AddItem() has two parameters:

  1. The Instance to be added to Debris.

  2. 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.

More information about this method here.

Ad
Log in to vote
0
Answered by
CJ4 2
5 years ago

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

Answer this question