Im pretty sure I have a memory leak or something but I may not me 100% sure, this script starts off being pretty good then becoming unusable in the matter of minutes, so there’s a major memory leak I believe. I just want a second pair of eyes to review my code to see if theres anything major I messed up on.
CONTEXT: This is AI script that follows the player, it isn’t fully done but this is a major issue I need done so I can add more later.
CLIENT:
local PFS = game:GetService("PathfindingService");
--Public Vars
local plr = game.Players.LocalPlayer;
local char = plr.Character or plr.CharacterAdded:Wait();
local PathObj = PFS:CreatePath();
--Functions
local function GetDst(Pos1, Pos2)
return math.sqrt((Pos1.X - Pos2.X)^2 + (Pos1.Y - Pos2.Y)^2 + (Pos1.Z - Pos2.Z)^2);
end
--Main
game.ReplicatedStorage.Events.TroopListen.OnClientEvent:Connect(function(TroopEvent)
TroopEvent.OnClientEvent:Connect(function(Path, Troop)
if (char) then
local StartPoint;
if (#Path > 0) then
StartPoint = Path[#Path].Position;
else
StartPoint = Troop.HumanoidRootPart.CFrame.Position;
end
PathObj:ComputeAsync(StartPoint, char.HumanoidRootPart.CFrame.Position);
local ReturnPoints = {};
local Waypoints = PathObj:GetWaypoints();
if #Waypoints < 4 or GetDst(StartPoint, char.HumanoidRootPart.CFrame.Position) < 10 then
TroopEvent:FireServer(ReturnPoints)
return
end
for i = 2, 5 do
if (Waypoints[i]) then
table.insert(ReturnPoints, Waypoints[i])
end
end
TroopEvent:FireServer(ReturnPoints)
end
end)
end)
SERVER:
--Services
local PFS = game:GetService("PathfindingService");
--//Public Vars
local UpdatePath = script.Parent.UpdatePath;
local Troop = script.Parent.Parent;
local Hum = Troop.Humanoid;
local Path = {};
local Owner = script.Parent.Owned;
local Debounce = false;
--//Functions
local function GetDst(Pos1, Pos2)
return math.sqrt((Pos1.X - Pos2.X)^2 + (Pos1.Y - Pos2.Y)^2 + (Pos1.Z - Pos2.Z)^2);
end
local function CheckPath()
local Char = Owner.Value.Character;
if (Char) then
if #Path <= 4 and GetDst(Troop.HumanoidRootPart.CFrame.Position, Char.HumanoidRootPart.CFrame.Position) > 10 then
if (Debounce == false) then
Debounce = true;
UpdatePath:FireClient(Owner.Value, Path, Troop);
end
end
end
end
--//Main
UpdatePath.OnServerEvent:Connect(function(plr, NewPath)
if (plr == Owner.Value) then
for i,v in pairs(NewPath) do
table.insert(Path, v);
end
Debounce = false;
end
end)
while true do
CheckPath();
print(#Path)
local Target = Path[1];
if (Target) then
local Char = Owner.Value.Character;
if (Char) then
local Dst = GetDst(Target.Position, Char.HumanoidRootPart.CFrame.Position);
if (not (Dst <= 10)) then
Hum:MoveTo(Target.Position);
if (Target.Action == Enum.PathWaypointAction.Jump) then
Hum.Jump = true;
end
Hum.MoveToFinished:Wait();
end
end
table.remove(Path, 1)
else
wait();
end
end
PS: Thanks for your time <3