Humanoid.Die function working wrong

I am making a respawn system, the first time it’s working but after that, it starts to respawn more than one time the same NPC.
script:

local function Respawn(NPC)
    local firstPos = NPC.HumanoidRootPart.Position
	local humanoid = NPC:WaitForChild("Humanoid")
    local Name = NPC.Name
	humanoid.Died:Connect(function()
		local FindDie = NPC.Animation.Die
		local RunAnim = NPC.Animation.Run
		local BreathAni = NPC.Animation.Breath
		local StartDie = humanoid:LoadAnimation(FindDie)
		local runAniTrack = humanoid:LoadAnimation(RunAnim)
		local breathTrack = humanoid:LoadAnimation(BreathAni)
	
		runAniTrack:Stop()
		breathTrack:Stop()
		NPC.HumanoidRootPart.Anchored = true
		StartDie:Play()
	
		wait(1.5)
		NPC:Destroy()
		wait(15)
		
		local npc = game.ServerStorage.Npcs:FindFirstChild(realName)
		if npc and workspace.NPCS:FindFirstChild(fakeName) == nil then
			local copy = npc:Clone()
			copy.Name = Name
			copy.Parent = workspace.NPCS
			copy:MoveTo(firstPos)
		    print(Name.." respawned")
		end
    end)
end

for _,child in pairs(workspace.NPCS:GetChildren()) do
	if child:IsA("Model") then
		Respawn(child)
	end
	wait()
end

workspace.NPCS.ChildAdded:Connect(function(child)
	if child:IsA("Model") then
		Respawn(child)
	end
end)
1 Like

I believe it’s because you are calling the Respawn function twice. Try calling the Respawn function once, see if that could fix the issue.

Let me know if this code works or not:

local function Respawn(NPC)
    local firstPos = NPC.HumanoidRootPart.Position
	local humanoid = NPC:WaitForChild("Humanoid")
    local Name = NPC.Name
	humanoid.Died:Connect(function()
		local FindDie = NPC.Animation.Die
		local RunAnim = NPC.Animation.Run
		local BreathAni = NPC.Animation.Breath
		local StartDie = humanoid:LoadAnimation(FindDie)
		local runAniTrack = humanoid:LoadAnimation(RunAnim)
		local breathTrack = humanoid:LoadAnimation(BreathAni)
	
		runAniTrack:Stop()
		breathTrack:Stop()
		NPC.HumanoidRootPart.Anchored = true
		StartDie:Play()
	
		wait(1.5)
		NPC:Destroy()
		wait(15)
		
		local npc = game.ServerStorage.Npcs:FindFirstChild(realName)
		if npc and workspace.NPCS:FindFirstChild(fakeName) == nil then
			local copy = npc:Clone()
			copy.Name = Name
			copy.Parent = workspace.NPCS
			copy:MoveTo(firstPos)
		    print(Name.." respawned")
		end
    end)
end

for _,child in pairs(workspace.NPCS:GetChildren()) do
	if child:IsA("Model") then
		Respawn(child)
	end
	wait()
end
2 Likes

It worked thank you, can you explain to me why I can’t understand why is that happening.

2 Likes

Yeah, so as I said above, you have called the Respawn function twice, one time in a for loop, and one time in the ChildAdded event. Because you were calling the Respawn function in the ChildAdded event, multiple Respawn functions would be running at once, which is basically why there were more NPC respawning than just one. Hopefully this is understandable.

2 Likes