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

Using spawn() function inside for loop?

function module.gamemode()
	for timer = timeLimit, 0, -1 do
		spawn(function()
			for _, map in pairs(workspace:WaitForChild("Castle Map"):GetChildren()) do
				if map:FindFirstChild("Flag") then
					local color = map.Flag.BrickColor
					if color == game.Teams.Red.TeamColor then
						redFlags = redFlags + 1
					elseif color == game.Teams.Blue.TeamColor then
						blueFlags = blueFlags + 1
					end
				end
			end	
			wait(3)	
		end)
		wait(1)
	end
end

What I have is a for loop which cycles through every second to count down the timer. However, I want every 3 seconds to give each team a point, depending who has control of the flag. The script is in a moduleScript

2 answers

You haven't really clarrified what your issue is, but I have a suggestion to make things a little easier for you.

If you use the new tagging system, you can find the 'map.Flag.BrickColor' value much easier, or call it a distinguishable name and use the second variable on the FindFirstChild function (which searches through the complete list of children in an item)

e.g. brick = game.Workspace.Model.Model.Brick OR brick = game.Workspace:FindFirstChild("Brick",true)

1 comment

0

I did say what was wrong. I want to have 2 for loops running simultaneously but with different wait times for each. The problem with my script is I dont know how to do that. I tried using a spawn() function, but that still makes the for loop for off 1 second

The problem is that you are spawning a new thread every for-loop-iteration (ie every second). Solutions:

  1. Use a while loop on a separate thread that continues until the game is over
  2. Only give a point when timer % 3 == 0 (you can make it more complex to make it more accurate, but this would be a simple method).
--Method 1
--when the game starts:
gameOn = true
spawn(function()
	while gameOn do
		wait(3)
		--your algorithm for awarding points here (without the wait(3))
	end
end
--when game ends:
gameOn = false

--Method 2
for timer = timeLimit, 0, -1 do
	if timer % 3 == 0 then
		--your algorithm for awarding points here (without the wait(3))
	end
	wait(1)
end

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