Yielded Coroutines Causing Lag?

  1. I’m working on a Bumper Cars game, and I am trying to have multiple cars running via coroutines without too much lag.

  2. After a player’s character is removed, the current running coroutine for that car is yielded, the car is deleted, and if the player respawns, another car and its required coroutines are recreated. But every time the player respawns, it becomes a little more laggy.

  3. Assuming yielded coroutines do cause lag, I need help finding a way to completely remove the coroutine from the game. If they do not, I will need other ideas of how respawns might cause lag?

Here’s the code I’m most suspicious of (It does seem a bit inefficient anyway, so are there any suggestions of how I can alternatively run this function? While letting the script continue handling the game)

-- ModuleScript
Car.RunEngine = function(player)
	local run = coroutine.wrap(function()
		while wait() do
			player.CharacterRemoving:connect(function()
				coroutine.yield()
			end)
			-- code for running the car engine
		end
	end)
	run()
end

coroutine functions and the Roblox scheduler (i.e. events, wait etc.) don’t play nice together, because the Roblox scheduler uses coroutines in its implementation. So what your call to coroutine.yield actually does is yield the coroutine created by the player.CharacterRemoving event handler - it does not yield the coroutine you created with coroutine.wrap, so your code isn’t actually stopped when the character is removed.

Also, this

                while wait() do
			player.CharacterRemoving:connect(function()
				coroutine.yield()
			end)

Creates a new connection to CharacterRemoving every tick. You only need one.

You want something like

Car.RunEngine = function(player)
    local stopped = false
    player.CharacterRemoving:connect(function() stopped = true end)
    Spawn(function()
        while not stopped do
            --code
            wait()
        end
    end)
end
1 Like

Yeah, thought it would be something along those lines. I’ll try it out :+1: