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

Why is the Generic For loop only playing things one by one?

For loops really hate me.

This script I made is supposed to make all the alarms in my place play at once when the OilPressure's value is greater than 3499. NLA is a model holding all the alarms, which are all named NauticalLightAlarm.

  • Workspace
    • NLA
      • NauticalLightAlarm
        • Light
          • PointLight
      • NauticalLightAlarm

The problem is that the generic for loop is only making the alarms play one by one in a sequence rather than all at once. When I use a normal for loop, only one alarm plays. How do I fix it?

gc = game.Workspace.NLA:GetChildren()

while true do
	wait(1)
	if game.Workspace.Config.OilPressure.Value > 3499 or game.Workspace.Config.GasPressure.Value > 3499 then
	on = true
	for i,v in pairs(gc) do
		if v.Name == "NauticalLightAlarm" then  
		while on do
		v.Light.PointLight.Enabled = true
		v.Light.Material = "Neon"
		v.Light.BrickColor = BrickColor.new("Really red")
		wait(0.75)
		v.Light.PointLight.Enabled = false
		v.Light.Material = "SmoothPlastic"
		v.Light.BrickColor = BrickColor.new("Dark stone grey")
		wait(0.75)
	end
	end
	end
	end
	end

2 answers

✓ Accepted answer

You're making a common "syncing" bug.

You can't do this in a single for loop, simply because each individual loop contains delays. To fix this, you have to move the delays outside of the loops, and re-loop each time.

gc = game.Workspace.NLA:GetChildren()

while true do
	wait(1)
	if game.Workspace.Config.OilPressure.Value > 3499 or game.Workspace.Config.GasPressure.Value > 3499 then
		on = true
		--First, the greater 'while on do' needs to be top-level!
		while on do
			--Next, we use a for loop to modify all the properties at once...
			for i, v in pairs(gc) do
				if v.Name == "NauticalLightAlarm" then
					v.Light.PointLight.Enabled = true
					v.Light.Material = "Neon"
					v.Light.BrickColor = BrickColor.new("Really red")
				end
			end
			---THEN wait()
			wait(0.75)
			--Then use the for loop again
			for i, v in pairs(gc) do
				if v.Name == "NauticalLightAlarm" then
					v.Light.PointLight.Enabled = false
					v.Light.Material = "SmoothPlastic"
					v.Light.BrickColor = BrickColor.new("Dark stone grey")
				end
			end
			--And the final wait()
			wait(0.75)
		end
	end
end

1 comment

0

Thanks a lot!

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