Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Best way to have multiple loops in a script running (at the same time)?

I'm familiar with 'spawn' and coroutines, but I'm not sure which are the best to use if I'm going to have several loops running at the same time in my code. My script is local, and it's purpose is to animate objects in workspace by simply rotating them to give them a motion effect. Here's my current work:

local sword_1 = workspace:WaitForChild("Sword1")
local sword_2 = workspace:WaitForChild("Sword2")
local sword_3 = workspace:WaitForChild("Sword3")

-- This is my main concern...
spawn(function()
	while wait() do
		sword_1.CFrame = sword_1.CFrame * CFrame.Angles(0,0,0.1)
	end
end)

spawn(function()
	while wait() do
		sword_2.CFrame = sword_2.CFrame * CFrame.Angles(0.1,0,0.1)
	end
end)

spawn(function()
	while wait() do
		sword_3.CFrame = sword_3.CFrame * CFrame.Angles(0,0.1,0)
	end
end)

So basically I'm just wondering if there's a better way to do this. This current method does work, but to me something just looks like it could be improved in both readability, and efficiency. Thanks for reading, hope you can help.

1 answer

Rather than using coroutines, condense your code and improve overall efficiency by simply combining all your while loops into a single loop.

local sword_1 = workspace:WaitForChild("Sword1")
local sword_2 = workspace:WaitForChild("Sword2")
local sword_3 = workspace:WaitForChild("Sword3")

while wait() do
	sword_1.CFrame = sword_1.CFrame * CFrame.Angles(0,0,0.1)
	sword_2.CFrame = sword_2.CFrame * CFrame.Angles(0.1,0,0.1)
	sword_3.CFrame = sword_3.CFrame * CFrame.Angles(0,0.1,0)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.