Coroutines and Script timeout: exhausted allowed execution time

How can I prevent my script from timing out while using Coroutines. I’m trying to utilize coroutines or something else to be able to use one script instead of having to paste it into 100 objects.
This is much easier than having to delete all the scripts for the objects and repasting every time I make changes.

I feel coroutines should be able to work without sever exhaustion because if I post the script in each object I can get it to work with 2500 objects without delay. Unlike with coroutine I can’t even get it to work with 4% of that.

while GAME_ACTIVE == true do
	for num, child in pairs(Layer1:GetChildren()) do
		coroutine.wrap(function()
		TileChange(child)
		end)()
	end
end

local function TileChange(child)
	local FallEvent = math.random(0,1)
	local Event = math.random(0,4)
	local BlockWait = math.random(0,10)
	if FallEvent == 0 then
		wait(BlockWait)
		child.BrickColor = BrickColor.new("Crimson")
		wait(2)
		child.Transparency = 1
		child.CanCollide = false
		wait(2)
		child.Transparency = 0
		child.CanCollide = true
		child.BrickColor = BrickColor.new("Medium stone grey")
	elseif Event >= 2 then
		local TilePosition = child.position
		wait(BlockWait)
		child.BrickColor = BrickColor.new("Really blue")
		wait(2)
		child.BrickColor = BrickColor.new("Medium stone grey")
	end
end

How could I possibly get coroutines to work here? Otherwise, could there potentially be another option?

while GAME_ACTIVE == true do
	for num, child in pairs(Layer1:GetChildren()) do
		coroutine.wrap(function()
		TileChange(child)
		end)
        wait()
	end
    wait()
end

Replace the while loop with what I posted above, that should fix it :slight_smile:

1 Like

Can’t believe how simple it was! Nonetheless, I appreciate it!