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 :)
while true do wait(0.2) local DISVALUE = script.Parent.Distance.Value local DEVALUE = script.Parent.DE.Value local partsW = game.Workspace:GetChildren() if DEVALUE == 1 then for i = 1,#partsW do if partsW[i]:IsA("Model") and partsW ~= script.Parent.Parent then local partsGet = partsW[i]:GetDescendants() for i = 1,#partsGet do if partsGet[i]:IsA("Part") or partsGet[i]:IsA("WedgePart") or partsGet[i]:IsA("UnionOperation") then local dis = (partsGet[i].Position-script.Parent.Position).Magnitude if partsGet[i].Name == "Destroyable" then if dis< script.Parent.Distance.Value then local thisisaPart = partsGet[i] thisisaPart.Anchored = false thisisaPart:BreakJoints() thisisaPart.Velocity = Vector3.new(math.random(-100,100),math.random(20,40),math.random(-100,100)) end end end end end end wait(2.5) end end
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:
for i = 1, 999 do print("lag ahhh") end
Non laggy loop:
for i = 1, 999 do print("no lag yay") wait() end
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.