玲嘉婕嘉n 发表于 2021-7-10 14:09:08

coroutine协程的问题

游戏中有一个使用技能,触发后能够减少当前处于cd中技能的冷却时间
在客户端cd限制中,cd的展示我使用了协程的方式。但是,当第一次调用冷却后,处于冷却中,再次调用,客户端显示上回会执行2个协程,我没办法中断上一个协程,我对协程理解非常有限,若有能实现方法更好的方式,请大佬赐教!

/uploads/default/original/2X/6/6cb70ef2a095651492b74c3cf02fcb008ecd8c50.mp4

1、模块
local CoolDownManager = {}
CoolDownManager.__index = CoolDownManager

function CoolDownManager.new_F()

local self = setmetatable({}, CoolDownManager)

self._running = false

return self

end
---方形cd
function CoolDownManager:coolDownAnimaF(Button,CD)
        if not self._running then
                local thread = coroutine.create(function()
                        self._running = true
                        Button.time.Text = CD
                        Button.cd.Visible = true
                        Button.icon.ImageColor3 = Color3.fromRGB(107, 107, 107)
                        local goal = {}
                        goal.Position = UDim2.new(0, 0,1, 0)
                        goal.Size = UDim2.new(1, 0,0, 0)
                        local info = TweenInfo.new(CD,Enum.EasingStyle.Linear)
                        local tween = TweenService:Create(Button.cd,info,goal)
                        tween:Play()
                        local counter = 0
                        while self._running and counter < CD do
                                wait(1)
                                counter = counter + 1
                                Button.time.Text = CD - counter
                                --print("--------"..CD)
                                --print(self._running)
                                if counter == CD then
                                        Button.time.Text = ""
                                        Button.icon.ImageColor3 = Color3.fromRGB(255, 255, 255)
                                        Button.cd.Visible = false
                                        Button.cd.Size = UDim2.new(1, 0,1, 0)
                                        Button.cd.Position = UDim2.new(0, 0,0, 0)
                                end
                        end
                        self._running = false
                        Button.time.Text = ""
                end)
                coroutine.resume(thread)
        else
                warn("Warning: timer could not start again as it is already running.")
        end
end

--重置状态为假
function CoolDownManager:stop()
        if self and self._running then
                self._running = false
        end
end
return CoolDownManager
页: [1]
查看完整版本: coroutine协程的问题