Hello. I made an NPC, yet it is lagging when the player turns. Here is my code:
local characters = {};
local closestCharacter = nil;
local closestCurrentMagnitude = math.huge;
local pathFindingService = game:GetService("PathfindingService");
local path = pathFindingService:CreatePath()
function child_Added(instance)
if not instance:IsA("Model") or game:GetService("Players"):GetPlayerFromCharacter(instance) == nil then return end;
if closestCharacter == nil then closestCharacter = instance end
local targetIndex = #characters + 1
local lastInstanceName = instance.Name;
table.insert(characters, targetIndex, instance)
repeat wait() until not instance.Parent
table.remove(characters, targetIndex)
end;
function waypoints_Play(waypoints)
local characterOnStart = closestCharacter
for _, v in ipairs(waypoints) do
local humanoid = script.Parent.Humanoid;
humanoid:MoveTo(v.Position)
if closestCharacter ~= characterOnStart then continue end
end
return
end;
function update_Target()
if not closestCharacter then return end;
if closestCharacter.Humanoid.Health == 0 then return end;
path:ComputeAsync(script.Parent.Torso.Position, closestCharacter.HumanoidRootPart.Position)
local wayPoints = path:GetWaypoints();
waypoints_Play(wayPoints)
closestCurrentMagnitude = (closestCharacter.HumanoidRootPart.CFrame.Position - script.Parent.Torso.CFrame.Position).Magnitude;
for _, v in ipairs(characters) do
if v ~= closestCharacter and (closestCharacter.HumanoidRootPart.CFrame.Position - script.Parent.Torso.CFrame.Position).Magnitude < closestCurrentMagnitude then
closestCharacter = v
closestCurrentMagnitude = (closestCharacter.HumanoidRootPart.CFrame.Position - script.Parent.Torso.CFrame.Position).Magnitude
end
end
end;
workspace.ChildAdded:Connect(child_Added)
while wait(0.3) do
update_Target()
end
Here is the video that shows how it lags:
https://streamable.com/vehp2u
Any help?