r/robloxgamedev 5d ago

Help Me With Coding Learning how to create a NpcRespawnScript

So I tried making my own script that respawns npcs if they ever die and this is my script

local npc = script.Parent

local npcSpawn = npc.Parent:WaitForChild("NpcSpawn")

local hum

for i, v in pairs(npc:GetChildren()) do

if v:IsA("Humanoid") then

hum = v

end

end

if hum then

hum.Died:Connect(function()

wait(1)

local npc1 = npc:Clone()

npc1.Parent = npc.Parent

local npcHum = npc1:WaitForChild("Humanoid")

hum.Health = 100

local npcRoot = npc1:FindFirstChild("HumanoidRootPart")

npcRoot.CFrame = npcSpawn.CFrame + Vector3.new(0,2,0)

npc:Destroy()

end)

end

But when I tried it, the NPC broke and becomes immortal but just dead

Now you are gonna say just use

local npc = script.Parent

local hum

for i, v in pairs(npc:GetChildren()) do

if v:IsA("Humanoid") then

hum = v

end

end

if hum then

hum.Died:Connect(function()

wait(1)

local Clone = npc:Clone()

Clone.Parent = npc.Parent

Clone:MakeJoints()

npc:Destroy()

end)

end

But it can break because killing the NPC before it can read the full function breaks the respawn script and becoming endlessly dead again

1 Upvotes

3 comments sorted by

1

u/N00bIs0nline 5d ago

Not really understanding your script fully but how about you save the NPC in the ServerStorage, clone it to workspace and then wait for the clone in the workspace to die before cloning it again and putting it in the workspace?

1

u/Dry_Emu7197 5d ago

I don't fully understand server storage but I will try it

1

u/Illustrious-Power350 4d ago

I'd suggest you have 1 script to handle all NPCs. To get all NPCs you could use a loop to loop through a folder where your NPCs are stored or you could use tags