Hello! I am trying to loop 500+ objects, but then it runs it will lag for 1 second, obviously i dont want that to happened, you can say i have bad PC, but i want to run my game on ANY device, so yeah. Here is example of my code:
local Folder = workspace.Folder -- lets say there is 500+ object in this folder
for i, Object in pairs(Folder:GetChildren) do
task.spawn(function()
-- Lets say there is tweening
task.wait(2)
-- Lets say there is another tweening
end)
end
I dont want to add wait() in my loop cuz it will take full loop to end from 0 seconds to 5
for _, object in folder:GetChildren() do
task.spawn(function()
-- Lets say there is tweening
end)
end
wait(2)
for _, object in folder:GetChildren() do
task.spawn(function()
-- Lets say there is another tweening
end)
end
You don’t need to use threads for this, just create a function that runs code that doesn’t yield(no task.wait) for multiple objects/instances at once, and seperate those calls from the waits:
local function runMultiple(objects: {Instance}, f: (Instance) -> ())
for _, object in pairs(objects) do f(object) end
end
--both of these functions should not contain any yielding/waiting
local function f1(object: Instance)
end
local function f2(object: Instance)
end
local Objects = workspace.Folder:GetChildren()
runMultiple(Objects, f1)
task.wait(2)
runMultiple(Objects, f2)
What is your goal exactly here? I mean, sure, you’re looping 500+ objects. But what are you doing to these objects exactly? If you’re moving/tweening them, couldn’t you just put all these objects inside of a single model and then move the model instead of moving each part by itself? That way, you only need to move one single thing (the model itself) instead of moving everything, which should reduce lag.
From what I understand, you don’t want to use a task.wait() because it would be too slow. Instead, you can make a counter to track what loop number you are on and run a task.wait() every 20 loops or so using the remainder function like so:
if math.fmod(i, 20) == 0 then
task.wait()
end
In this case, “i” is the loop number and 20 would be how often you want to task.wait(), in this case that would be once every 20 loops. This would prevent your game from freezing when doing large loops
Hi there! I made a topic not too long ago showing how you can move your parts with a high FPS rate! Here is the topic I made.
I hope it isn’t too long, but I do have a TL;DR part for it! I tested a lot of methods and maybe this will help you too! I recommend going through most of it to understand some side info that might be useful to you later as you continue developing! I hope this helps! It will work for tweening too!
You can use a WeldConstraint for the best performance.