I have a script that I created that detects when an npc in my game takes damage, then checks if the damage was fatal so that a ragdoll can take place. However, I’m not happy with how the code looks and would love a revision for learning purposes.
Script:
local npcFolder = workspace.NPCs.CommonNPCs
local function checkForDeath(npc)
local humanoid = npc and npc:FindFirstChildWhichIsA("Humanoid")
if humanoid then
humanoid.Died:Connect(function()
end)
end
end
for _, npc in npcFolder:GetChildren() do
checkForDeath(npc)
end
npcFolder.ChildAdded:Connect(function(child)
checkForDeath(child)
end)
Use Humanoid.Died, and connect the ragdoll function to the died event.
I don’t think you should check for the NPC existence anyway, it seems you have a special folder where you only add NPCs (you use the ChildAdded event which will never return you a nil child).
local function add_ragdoll(npc)
npc:FindFirstChildOfClass("Humanoid").Died:Connect(function()
-- Ragdoll code.
end)
end
for _, npc in pairs(npcs) do
add_ragdoll(npc)
end
workspace.NPCs.CommonNPCs.ChildAdded:Connect(function(child)
add_ragdoll(child)
end)
also, you should check if the health is changed AND call the function, not call and check cause it will run only when the child is added, this means that if the npc get another type of damage this wont detected
you should make a variable that checks the old npc Health
local OldHealth --create the variable
local function checkForDeath()
if OldHealth > Humanoid.Health --checks if the old health is bigger that the one right now
print("this hurt")
end
hu:GetPropertyChangedSignal("Health"):Connect(function()
OldHealth = Humanoid.Health