Is this to much for the heartbeat function?

I’m a new dev and can’t tell if my heartbeat function is being overworked

This script uses the heartbeat function to tell if a npc or player has died and then respawns them.

local function handleCharacter(character: any)
	if character:IsA("Model") and character:FindFirstChild("Humanoid") then
		
		local IsEnemy = character:GetAttribute("IsEnemy")
		
		local player = Players:GetPlayerFromCharacter(character)
		
		local botClone = nil
		
		local Humanoid = character:WaitForChild("Humanoid")
		
		local rootPart = character:FindFirstChild("HumanoidRootPart")
		Humanoid:SetStateEnabled(Enum.HumanoidStateType.Dead, false)

		local isdead = false
		
		local npcClone = character:Clone()
		
		character:SetAttribute("Ragdolled", false)
		character:SetAttribute("Aerial", false)
	
		local function deathcheck()
			if isdead then
				return
			end
			if Humanoid.Health > 0 and rootPart.Position.Y >= -500 then
				isdead = false
				return
			else
				isdead = true

				coroutine.wrap(RagdollService.RagdollCharacter)(character, 2000, true)
				print("died")

				task.wait(5)

				print("respawned")

				if player then
					respawnCharacter(player)
				else
					character:Destroy()

					npcClone.Parent = Workspace.Characters

					handleCharacter(npcClone)
				end
			end
		end

		RunService.Heartbeat:Connect(function()
			deathcheck()
		end)
		
	end
end
1 Like

depends if it respawn characters every heartbeat then its overworked but if it only respawns like 1 out of 10 then its fine ig.

1 Like

Just curious is there a reason you cant use the Humanoid.Died event? This shouldn’t be too much but I don’t see much point in doing it like this.

In the deathcheck function, you are checking if the health is greater than zero and the player is not in/under the void. This is all unneccessary, as this is already checked by roblox’s own framework. I suggest using the simplest way, which is using the Humanoid.Died event.

local function handleCharacter(character: any)
	if character:IsA("Model") and character:FindFirstChild("Humanoid") then
		local IsEnemy = character:GetAttribute("IsEnemy")
		local player = Players:GetPlayerFromCharacter(character)
		local botClone = nil
		local Humanoid = character:WaitForChild("Humanoid")
		local rootPart = character:FindFirstChild("HumanoidRootPart")
		Humanoid:SetStateEnabled(Enum.HumanoidStateType.Dead, false)
		local isdead = false
		local npcClone = character:Clone()
		character:SetAttribute("Ragdolled", false)
		character:SetAttribute("Aerial", false)
		
		Humanoid.Died:Connect(function()
			isdead = true
			coroutine.wrap(RagdollService.RagdollCharacter, character, 2000, true)
			print("died")
			task.wait(5)
			print("respawned")
			if player then
				respawnCharacter(player)
			else
				character:Destroy()
				npcClone.Parent = Workspace.Characters
				handleCharacter(npcClone)
			end
		end)
	end
end