How to make multiple of the same function run at the same time using coroutines

So I know it may revolve around coroutines but I couldn’t coroutine.wrap my head around it, so I need help on making multiple of the same function run at the same time using coroutines.
Here’s my code.

local a = script.Parent.Frame.ImageLabel.Frame.a

local b = script.Parent.Frame.ImageLabel.Frame.b

local c = script.Parent.Frame.ImageLabel.Frame.c

local d = script.Parent.Frame.ImageLabel.Frame.d

local e = script.Parent.Frame.ImageLabel.Frame.e

function du(v)

v:TweenSizeAndPosition(UDim2.new(.2,0,.2,0),UDim2.new(v.Position.X.Scale-.025,0,v.Position.Y.Scale-.025,0),"Out","Sine",.45)

wait(.6)

v:TweenSizeAndPosition(UDim2.new(.15,0,.15,0),UDim2.new(v.Position.X.Scale+.025,0,v.Position.Y.Scale+.025,0),"Out","Sine",.45)

end

while wait() do

du(a)

wait(.05)

du(b)

wait(.05)

du(c)

wait(.05)

du(d)

wait(.05)

du(e)

wait(.5)

end

This article explains coroutines in an easy way to understand. Basically, you’ll need to use coroutine.create() and coroutine.resume() or coroutine.warp() (The way I used for the example script).
If you want to patch it into the script, do the following:

local TweenFunction = coroutine.warp(function(v)

v:TweenSizeAndPosition(UDim2.new(.2,0,.2,0),UDim2.new(v.Position.X.Scale-.025,0,v.Position.Y.Scale-.025,0),"Out","Sine",.45)

wait(.6)

v:TweenSizeAndPosition(UDim2.new(.15,0,.15,0),UDim2.new(v.Position.X.Scale+.025,0,v.Position.Y.Scale+.025,0),"Out","Sine",.45)

end)

-- After that, call the function and add in the v
1 Like

image

I had a mistake in the script, I fixed it now.

That ) is not the point, the coroutine only works first time. Then it shows an error that says it’s dead

Ah, forget it. I’m just going to make use of external events. I’ll change it once someone finds a solution

So coroutines are just temporary threads that allow you to execute asynchronously from the main thread of your script.

Just like a script, once they reach their end, they return, and stop/die.

If you want to run the same function over and over asynchronously what you should do is something akin to this:

--- This function could be anything from an external function stored in a module, to a local one
local function FuncA(parm1, parm2, ...)
     print('memes')
end

-- Anytime you want to run it, simply wrap it in a coroutine and immediately fire it
coroutine.wrap(FuncA)(parm1, parm2, ...)

--It's a lot simpler to reference an existing function as above than creating new anonymous coroutines as below:
coroutine.wrap(function(parm1, parm2, ...)
     print('memes')
end)(parm1, parm2, ...)
-- Saves on memory too!

Best of luck!

5 Likes