#Help with npc respawning
8 messages · Page 1 of 1 (latest)
I have a rig which chases me around and I implemented a function so that it respawns if it dies but more than one npc respawns and it multiplies each time
Here's my script
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local rootPart = npc:WaitForChild("HumanoidRootPart")
local Players = game:GetService("Players")
local respawnTime = 3
local npcSpawnPoint = rootPart.Position
local npcClone = npc:Clone()
local walkSpeed = 50
local function getNearestPlayer()
local nearestPlayer = nil
local shortestDistance = math.huge
for _, player in pairs(Players:GetPlayers()) do
local character = player.Character
if character and character:FindFirstChild("HumanoidRootPart") then
local distance = (rootPart.Position - character.HumanoidRootPart.Position).magnitude
if distance < shortestDistance then
shortestDistance = distance
nearestPlayer = character
end
end
end
return nearestPlayer
end
local function followNearestPlayer()
while humanoid.Health > 0 do
local target = getNearestPlayer()
if target then
humanoid:MoveTo(target.HumanoidRootPart.Position)
humanoid.WalkSpeed = walkSpeed
humanoid.MoveToFinished:Wait()
end
wait(0.05)
end
end
local function respawnNPC()
wait(respawnTime)
local newNPC = npcClone:Clone()
newNPC.Parent = npc.Parent
newNPC:SetPrimaryPartCFrame(CFrame.new(npcSpawnPoint))
script.Parent = newNPC
newNPC:FindFirstChild("Humanoid").Died:Connect(respawnNPC)
followNearestPlayer()
end
humanoid.Died:Connect(respawnNPC)
followNearestPlayer()
thats because
you clone the NPC
so it has the script which runs this
but then u ALSO wait for that one to die here
I wouldn't advise you to put the script inside the NPC as it can glitch or fall into the void and once it's deleted the script will too (a good chance that it will, not sure if it actually would)
A safer approach is to place both script and NPC in a folder at ServerStoarge and copy paste it from there to the workspace, ensuring that the NPC is untouched and not a duplicate of a dead or damaged one in a different location.
** You are now Level 1! **