Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I prevent the lag spike from this script?

Asked by 5 years ago
Edited 5 years ago

I've already asked this question before but I had no luck with answers. So basically I've been working on this script that finds other parts named "Destroyable," and so when the "Destroyable" part is within range of the destruction part (where this script is located,) it moves it around. Now I know making parts move around will cause lag, but I'm not concerned about that. What I am concerned about, however, are the annoying lag spikes this script causes, I'm pretty sure it's because of GetChildren() and GetDescendants() but I need them to find the parts and such. If there's another way to do this without using them both please help. Thank you for reading :)

01while true do
02wait(0.2)
03local DISVALUE = script.Parent.Distance.Value
04local DEVALUE = script.Parent.DE.Value
05local partsW = game.Workspace:GetChildren()
06if DEVALUE == 1 then
07for i = 1,#partsW do
08    if partsW[i]:IsA("Model") and partsW ~= script.Parent.Parent then
09        local partsGet = partsW[i]:GetDescendants()
10        for i = 1,#partsGet do
11            if partsGet[i]:IsA("Part") or partsGet[i]:IsA("WedgePart") or partsGet[i]:IsA("UnionOperation") then
12                local dis = (partsGet[i].Position-script.Parent.Position).Magnitude
13                if partsGet[i].Name == "Destroyable" then
14                if dis< script.Parent.Distance.Value then
15                    local thisisaPart = partsGet[i]
View all 27 lines...

2 answers

Log in to vote
0
Answered by
rower86 35
5 years ago

Your for loops do not have a wait on them, which tells the script to perform every loop as fast as possible lol

Lag spike machine:

1for i = 1, 999 do
2    print("lag ahhh")
3end

Non laggy loop:

1for i = 1, 999 do
2    print("no lag yay")
3    wait()
4end
0
yeah but then u need to wait HappyTimIsHim 652 — 5y
0
HappyTimlsHim, it waits the exact same time it runs the script without the wait (unless you put something more than a 0 in the wait) bostaffmanbulgaria1 89 — 5y
0
The default value of wait is ~ 0.16, calling wait without any parameters uses this default value instead ankurbohra 681 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

Your loop is going through a lot of instances, you should be using folders to organise your Workspace so you look through only what needs to be looped through. At the time of creation, add your “Destroyable” parts In a folder or use the CollectionService:AddTag() and CollectionService:GetTagged() methods to minimise the number of objects you loop through, while also omitting several checks.

Answer this question