How can I improve this NPC Respawn?

I have a few combat dummies that I wanna respawn when they die and this is the code I ended up doing for it.

local RESPAWN_TIME = 3

local dummyFolder = script.Dummies

local function onDied(originalDummy, oldDummy)
	local newDummy = originalDummy:Clone()
	oldDummy:Destroy()
	task.wait(RESPAWN_TIME)
	newDummy.Parent = workspace.Game.NPC
	
	newDummy.Humanoid.Died:Connect(function()
		onDied(originalDummy,newDummy)
	end)
end

for _,dummy in pairs(dummyFolder:GetChildren()) do
	local dummyClone = dummy:Clone()
	dummyClone.Parent = workspace.Game.NPC
	
	dummyClone.Humanoid.Died:Connect(function()
		onDied(dummy,dummyClone)
	end)
end

It works fine, but it doesn’t feel like the cleanest/best way to do this.

1 Like

Im assuming the dummys are all the same, you can use the same model and clone it to different places. I would keep a table with dummy spawn locations and clone to each and attach the event to that, just make sure to disconnect the events when the dummy dies to prevent memory from building up.

local Spawns = {(1,2,3),(4,5,6)}
local DummyModel = game.ServerStorage.Dummy
local Clone
-- Initialise Dummys
for i = 1,#Spawns do
    Clone = MakeDummy(Spawns[i],i)
    -- Connect Death to current loop
    Clone.Destroyed:Connect(function()
        -- Respawn This Clone
        MakeDummy(Spawns[i],i)
    end

local function MakeDummy(Pos,ID)
    Clone = DummyModel:Clone()
    Clone.Parent = game.workspace.Dummys
    Clone.Position = Pos
    Clone.Name = "Dummy" .. tostring(ID)
    return Clone
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.