When should we use coroutines

Something to clarify is that I already know what a coroutine is, how it works and what it is for, but I have not been able to think of a situation in which I need to use it for a function or mechanic in a game, I would like you to give me cases in which you They have come to use them, for what type of mechanics and if it was of much use to them, also tell me in what type of game mechanics or systems coroutines are usually used a lot.

3 Likes

I believe the main appeal is you can prepare a thread, being able to capture variables from the current point, but then being able to hold on to it as a variable and launch it later. With task.spawn the thread launches immediately.

1 Like

2 loops in the same script.

coroutine.wrap(function()
while true do
print("Loop 1")
end
end)

while true do
print("Loop 2")
end
4 Likes

They allow to skip over any waits or yields. For exampe,

local co = coroutine.create(function()

	workspace.AttributeChanged:Wait()
	
	print("Nah, ain't nobody got time for that")
	
	workspace.Camera.AttributeChanged:Wait()
	
	print("Did the cam change or no?")
	
end)


coroutine.resume(co)

workspace.Camera:SetAttribute("AUselessAtt",true)  --  nothing prints ofc 


wait(15)


coroutine.resume(co)


workspace.Camera:SetAttribute("AUselessAtt",false)  --  nothing prints ofc





1 Like

Yes, but what I want to know is what kind of things I would need to use coroutines for, for example if for a tool, a vehicle, a tycoon and why, that’s what I mean, if you have ever used a coroutine I would like to know For what exactly, for a rounds system? For a combat system? A realistic car? etc., that’s what I was referring to with my question, because I already know how coroutines work, but I don’t know in what mechanics in my game I would need to use it.

I dont get the difference between coroutines and task.spawn

One use case for it is to make a spinning GUI while something saves or loads.

Example in my script
local function CoroutineFunction() --This function just rotates a GUI until the coroutine is closed
	LoopIcon.Visible = true
	while task.wait() do
		if LoopIcon.Rotation ~= -180 then
			LoopIcon.Rotation -= 0.2
		else
			LoopIcon.Rotation = 0
		end
	end
end

script.Parent.MouseButton1Click:Connect(function()
    coroutine.resume(CoroutineFunction)
    --The rest of the data saving stuff here
    coroutine.close(CoroutineFunction)
end)

(Please tell me if there are better ways to do this)

2 Likes

its a very good example thanks

1 Like

Another useful feature of coroutines is, say you need to fetch some data from the server using a RemoteFunction. If you use a coroutine, you will be able to continue executing some code while you wait to receive the data from the server like so:

coroutine.wrap(function()
   local data = remoteFunction:InvokeServer()
   —do something with the data received
end)()

—do something else without needing to wait for the data
2 Likes