Unable to check each NPC Health

Provide an overview of:

  • What does the code do and what are you not satisfied with?
    This code is sopposed to spawn a max of 10 NPCs and when a player destroys one of them another spawns up to its max amount. But the line where it checks the NPCs health is equal to 0 doesn’t work. I assume it may because I’m checking the health of one NPC and not all of them. Any ideas on how to manage this?

local serverStorage = game:GetService(“ServerStorage”)
local mob = serverStorage:FindFirstChild(“Rig”)

local testFolder = workspace.TestFolder
local spawnPart = workspace.MobSpawn
local cloneAmount = #testFolder:GetChildren()
local maxAmount = 9

for i = cloneAmount, maxAmount, 1 do
	wait()
	local clone = mob:Clone()
	clone:FindFirstChild("HumanoidRootPart").Position = spawnPart.Position
	clone.Parent = testFolder
	print("cloned character")

	if cloneAmount == maxAmount then
	break
end

end

print("done")

if testFolder:FindFirstChild("Rig"):WaitForChild("Humanoid").Health == 0 then
	for i = cloneAmount, maxAmount, 1 do
		wait()
		local clone = mob:Clone()
		clone:FindFirstChild("HumanoidRootPart").Position = spawnPart.Position
		clone.Parent = testFolder
		print("cloned another character")
		if maxAmount == maxAmount then
		print("done")
		break
	end
end

end

2 Likes

Use Humanoid.Died to detect when humanoid dies

local ServerStorage = game:GetService("ServerStorage")

local MOB_RIG = ServerStorage:FindFirstChild("Rig")
local MAX_AMOUNT = 10
local TEST_FOLDER = workspace.TestFolder
local SPAWN_PART = workspace.MobSpawn

local function SpawnMob()
    local clone = MOB_RIG:Clone()
    local cloneHumanoid : Humanoid = clone:FindFirstChild("Humanoid")
    local cloneHumanoidRootPart = clone:FindFirstChild("HumanoidRootPart")

    cloneHumanoidRootPart.Position = SPAWN_PART.Position
    clone.Parent = TEST_FOLDER
    
    cloneHumanoid.Died:Once(function()
        SpawnMob()
    end)
end

for _ = 1, MAX_AMOUNT do
    SpawnMob()
end
2 Likes

You could try using the Humanoid.HealthChanged function.
This code should give you an idea:

Humanoid.HealthChanged:Connect(function(health)
	if hum ~= nil and health >= 0 then
		print(health)
		return health
	end
end)

This code above does the obvious, detects when the character’s health is changed, then when the health is changed, it will print out how much health the character has left. This is followed by checking if the humanoid in the character is available (or not nil), and this also checks if the character’s health is greater than or equal to 0.

Thanks for the suggestion I’ll take note of that.

1 Like

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