NPC Follow system works but after death it stops working [?]
Asked by
8 years ago Edited 6 years ago
Goal:
My goal is to create an NPC follow system (I already have the damage system completed). What it should do it if you are within a certain range measured by magnitude you are chased by some NPC's that are within range.
Problem:
The problem is when a Player first spawns in the NPC chases the player and everything but when the player Dies by something (NPC, another player) the NPC's stop chasing the player. The code works but it stops working sometimes.
Script:
Note that this is a ServerScript
in ServerScriptService
01 | local RunService = game:GetService( "RunService" ) |
02 | local Settings = require(game:GetService( "ReplicatedStorage" ).ModuleScripts.SETTINGS) |
03 | local Respawn_Time = Settings.BANDIT.RESPAWN_TIME |
04 | local plrServ = game:GetService( 'Players' ) |
05 | local NPCBackup = game:GetService( 'ServerStorage' ).NPCBackup.Bandit |
07 | local function getClosestPlayer(myPos) |
08 | local pos, tor = Settings.BANDIT.RANGE |
09 | for _, plr in pairs (plrServ:GetPlayers()) do |
11 | if (plr.Character.PrimaryPart.Position - myPos).Magnitude < pos then |
12 | pos = (plr.Character.PrimaryPart.Position - myPos).Magnitude |
13 | tor = plr.Character.PrimaryPart |
20 | local function setupNPC(Bandit, BanditPosition) |
22 | local hum = Bandit.Humanoid |
23 | local npcPrimaryPart = Bandit.PrimaryPart |
27 | targetTorso = getClosestPlayer(npcPrimaryPart.Position) |
29 | hum:MoveTo(targetTorso.Position, targetTorso) |
36 | hum.Died:Connect( function () |
37 | wait(Settings.BANDIT.RESPAWN_TIME) |
38 | local cln = NPCBackup:Clone() |
39 | cln:SetPrimaryPartCFrame(BanditPosition) |
40 | cln.Parent = workspace.Bandits |
42 | setupNPC(cln, BanditPosition) |
43 | if not cln:FindFirstChild( 'RobloxAnimation' ) then |
44 | local Animation = game:GetService( 'ServerStorage' ).Effects.RobloxAnimation:Clone() |
45 | Animation.Disabled = false |
46 | Animation.Parent = cln |
47 | cln.Humanoid.WalkSpeed = Settings.BANDIT.WALKSPEED |
52 | for _, Bandit in pairs (workspace.Bandits:GetChildren()) do |
53 | spawn( function () setupNPC(Bandit, Bandit.PrimaryPart.CFrame) end ) |
Hopefully, this problem gets solved, I appreciate any feedback that fixes this issue or improves the code. I try avoiding loops and RunService mostly because I do not know when is the correct time to use a while true do
loop and I know that using a loop incorrectly can be studio crashing and game breaking. Thank you for reading.