(Solved) Simplifying A Code For Many Instances Inside One Folder

Henlo, I just followed a tutorial on how to make a conveyor, it did work, until later I frustated getting the code works for many conveyors inside 1 folder. I was looking many forums here and there to find a solutions for this, and I finally manage to adapt it to mine, after like 2 hours :smiley:

This is the code from mine. I feel like the code might feel a bit too much because there is 2 usage of for loops. Is there any way to make it simplier? Or this one is already okay? I’m still a bit new at scripting.

local Workspace = game:GetService("Workspace")
local ConveyorFolder = Workspace:WaitForChild("ConveyorParts") --Folder for the conveyors.
local ConveyorParts = ConveyorFolder:GetChildren()

local function drag()
	for _, conveyors in pairs(ConveyorParts) do
		conveyors.AssemblyLinearVelocity = conveyors.CFrame.LookVector * 100
		task.wait(0.1)
	end
end

for _, conveyorPart in pairs(ConveyorParts) do
	if conveyorPart:IsA("BasePart") then
		conveyorPart.Touched:Connect(drag)
	end
end

move this code inside for loop in drag function then remove the other for loop that originally connects the touched event to drag function

WaitForChild is unnecessary/optional if the instance already exists in both editor and in game

use workspace or game.workspace if the service isnt altered and only for testing

Woah, it look simplier and worked nicely :0
Thanks!

local ConveyorFolder = game.Workspace.ConveyorParts
local ConveyorParts = ConveyorFolder:GetChildren()

local function drag()
	for _, conveyors in pairs(ConveyorParts) do
		conveyors.AssemblyLinearVelocity = conveyors.CFrame.LookVector * 100
		task.wait(0.1)
	end
end

drag()

And I thought the WaitForChild() function is necessary, glad to know it only used for something like Instance.new() when the part is created from the on-going server/client.