How can I optimize this code?

Hello, I have an issue, this part of code overload the server, is there a way to optimize this code?

for _, Object in pairs(Model:GetChildren()) do
	if Object.Name ~= "Root" then
		task.spawn(function()
			Object.Touched:Connect(function(part)
				if part.Name == "Flower" and PData.Vars.Field ~= "" then
					module:CollectFlower(Player, part, Args.StatsModule)
				end
			end)
		end)
	end
end
1 Like

Yes, there is.

local objects = Model:GetChildren() -- Get all children once
for _, Object in pairs(objects) do
    if Object.Name ~= "Root" then
        Object.Touched:Connect(function(part)
            if part.Name == "Flower" and PData.Vars.Field ~= "" then
                module:CollectFlower(Player, part, Args.StatsModule)
            end
        end)
    end
end

The code of MrFergxl should fix the problem because you’re creating a coroutine for every object inside your model that isn’t named Root and creation a lot of coroutines makes the game laggy

  1. Utilize CollectionService to iterate through all Objects that have a Tag, this will make the search faster, and more efficient than having to look through everything inside an object to find it.

  2. Skip the Iteration if the conditions are not met by using continue

if Object.Name == "Root" then continue end
-- skips the code if no condition is met.

unlike break which exits the loop, continue will completely skip the code in the loop to move on to the next iteration.


This will not change anything.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.