So I made a game here which you can check it out in this post. When I was playing it, I discovered some memory leaks that I have to prevent it in order to make my game performant. However, I couldn’t tell what’s wrong with my script that is causing these memory leaks.
Client’s memory leaks:
Server’s memory leaks:
And here is the script I suspect it causing these:
(this script handles the backend of the rocket bullet being shot by the rocket launcher itself after the client fires the remote event by clicking the tool)
RemoteEvent.OnServerEvent:Connect(function(plr,pos,handlePos)
-- settings
local explosionDisconnected = false
--print("fired")
local rocket = ServerStorage.Rocket:Clone()
rocket.Parent = workspace
--print(rocket.Parent.Name)
-- setting up rocket
rocket.CFrame = CFrame.new(handlePos,pos)
-- setting velocity
local direction = (pos - handlePos).Unit
rocket.BodyVelocity.Velocity = direction * speed
-- setting explosion
local explosion = Instance.new("Explosion")
explosion.BlastPressure = 10000
explosion.BlastRadius = 13
-- setting up fire
rocket.Touched:Connect(function(hit)
if not workspace.Targets:FindFirstChild(hit.Name,true) or hit.Name == "Handle" then -- hit us
return
else
if hit:IsA("BasePart") then hit.Anchored = false end
local CloneFire = rocket.Fire:Clone()
explosion.Position = rocket.Position
explosion.Parent = workspace
-- destroy this part or not?
local DestroyOrNot = RNG:NextInteger(0,1) == 1 and true
--print(DestroyOrNot)
if DestroyOrNot then
hit:Destroy()
else
CloneFire.Parent = hit
end
Debris:AddItem(CloneFire,RNG:NextInteger(10,30))
end
end)
local explosionConnection
explosionConnection = explosion.Hit:Connect(function(hit)
if not explosionDisconnected then
explosionDisconnected = true
task.defer(function()
task.wait(explosionTimeout)
explosionConnection:Disconnect()
end)
end
if not workspace.Targets:FindFirstChild(hit.Name,true) or hit.Name == "Handle" then -- hit us
return
else
if hit:IsA("BasePart") then hit.Anchored = false end
local CloneFire = Instance.new("Fire")
CloneFire.Color = Color3.fromRGB(RNG:NextInteger(0,255),RNG:NextInteger(0,255),RNG:NextInteger(0,255))
CloneFire.SecondaryColor = Color3.fromRGB(RNG:NextInteger(0,255),RNG:NextInteger(0,255),RNG:NextInteger(0,255))
explosion.Position = rocket.Position
rocket:Destroy()
explosion.Parent = workspace
-- destroy this part or not?
local DestroyOrNot = RNG:NextInteger(0,5) == 1 and true -- 20% chance to destroy
--print(DestroyOrNot)
if DestroyOrNot then
hit:Destroy()
else
CloneFire.Parent = hit
end
Debris:AddItem(CloneFire,RNG:NextInteger(10,30))
end
end)
-- finalizing
rocket.Parent = workspace
-- timeout if rocket did not reach anything
Debris:AddItem(rocket,10)
--print("finishd")
end)
Variables speed
, RNG
, and explosionTimeout
are outside the scope of this function, which is a small cause for the memory leaks, but I believe this function is responsible for the majority of the memory leaks.
Please give me any suggestion on how to prevent it. Thanks.