Is this efficient? Coroutine!

Partial code

function punch()
	debounce1=true
	PUNCH_TEXT.Text=punchCooldown
	PUNCH_TEXT.Parent.Visible=true
	local co1,co2
	co1=coroutine.create(function()
		punchAnimation:Play()
		coroutine.yield()
	end)

	co2=coroutine.create(function()
		for i=punchCooldown,0,-1 do
			PUNCH_TEXT.Text=i
			wait(1)
		end
		PUNCH_TEXT.Parent.Visible=false
		debounce1=false
		coroutine.yield()
	end)
	coroutine.resume(co1)
	coroutine.resume(co2)
end

first corourine do punch animation whereas 2nd one set the text of an text label, on each iteration.
all of these placed inside a function which means the variables will be removed after the task is done!

What I want to know is,

  • whether I am doing something wrong here?!

  • is it a waste to use coroutine in this scenario?

1 Like

Using coroutines here might not be necessary because the tasks you’re running (playing an animation and updating text) do not heavily demand concurrency control.

I modified your script a bit

function punch()
    debounce1 = true
    PUNCH_TEXT.Text = punchCooldown
    PUNCH_TEXT.Parent.Visible = true
    
    -- play punch animation
    punchAnimation:Play()

    -- text 
    spawn(function()
        for i = punchCooldown, 0, -1 do
            PUNCH_TEXT.Text = i
            wait(1)
        end
        PUNCH_TEXT.Parent.Visible = false
        debounce1 = false
    end)
end

In this code, spawn is used to run the countdown text update in a separate thread, allowing the animation to play concurrently without blocking and using coroutine. The code is simpler and avoids the potential pitfalls of using coroutines, like managing their state and etc.

1 Like

What if I use separate local scripts? for each task
one for animations
one for setting cooldown
and
one for doing damage (ofc i am gonna implement this in the server side)

What about communication between scripts?
This can also impact performance…
Also, with more scripts there are more things to manage so it’s hard to manage all the scripts yk
I would not recommend using multiple scripts for it, but the choice is yours.

1 Like

thank you for your time, this helped me thanks
@MRBEGI
one last question, can i use as many spawn function as necessary?

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.