Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

why doesn't this NPC move towards the player after he dies?

I made an NPC that follows you to kill you, but when you kill it, you respawn, and ten seconds later he respawns, but he stops following you. I think it has to do with the game.Players.PlayerAdded function but that is the only way I know. The script is inside the NPC

game.Players.PlayerAdded:Connect(function(p)
p.CharacterAdded:Connect(function(char)
while true do
wait(0.1)
if p:DistanceFromCharacter(script.Parent.HumanoidRootPart.Position) < 90 then
script.Parent.Humanoid:MoveTo(char.HumanoidRootPart.Position)
end
end
end)
end)

10 comments

0

When a player resets, their character disappears. So whenever the NPC tries to follow the character, the character is nil.

0

If that's the problem, then how can I make it so that the character is not nil when the player respawns

0

p:WaitForChild("Character")

0

I tried that and p.Character but they both don't work

0

You can instead check if the HumanoidRootPart is nil: if p.Character:FindFirstChild("HumanoidRootPart") then

0

Okay so now it detects the HumanoidRootPart but he won't move

0

Do this: script.Parent.Humanoid:MoveTo(char.HumanoidRootPart.Position, char.HumanoidRootPart)

0

MoveTo() on the Humanoid has two parameters. The first is the point (Vector3) the Humanoid is trying to walk to, and the second is the part that's it's trying to walk to.

0

It doesn't seem to want to do anything

0

Oh, now I see. DistanceFromCharacter() is always calculating below 90 because the character being reset, which means that it's constantly calculating 0. And because the Character is nil when that condition is met, the NPC never moves. You have to check if the distance is above 0 before moving the NPC.

1 answer

✓ Accepted answer
function ready(tmp_plr)
game:GetService("RunService").Stepped:connect(function()
local yes, error = ypcall(function()
if (math.abs((tmp_plr.Character.Head.Position-script.Parent.Head.Position).magnitude)) < 90) then
script.Parent.Humanoid:MoveTo(tmp_plr.Character.Head.Position)
end
end)
end)
end    
game.Players.PlayerAdded:Connect(function(p)
ready(p)
end)

2 comments

0

Using RunService won't break the code if there's an error, further ypcall protects any errors from breaking the code. You only need to call the function once and that is when the player is added.

0

I'm sorry, why are you breaking the error function?

This discussion is preserved as it was. New answers, comments, and votes are closed.