协程问题

Coroutine problems

所以我试图在 ROBLOX 中制作一个基本的 GUI 动画系统,使用单独的帧和一个循环将它们放入图像标签中。

这是函数:

local playAnimation = coroutine.create(function(anim,pos,tank)
    while true do
    local animBase = sp.AnimBase:Clone()
    animBase.Parent = tank
    animBase.Visible = true
    animBase.Position = pos -- line that causes the error mentioned below.
    local frame = 1
    for i = 0, animations[anim]["FrameNum"] do
        frame = frame + 1
        animBase.Image = animations[anim]["Frames"][frame]
        NewWait(.1) --this right here, the wait, interfears with the yield.
        if frame >= animations[anim]["FrameNum"] then
            pos,anim,tank = coroutine.yield()
            break
        end
    end
    animBase:Destroy()
    end
end)

这有两个主要问题: 每次 运行s,我都会收到此错误:

20:41:01.934 - Players.Player1.PlayerGui.ScreenGui.Gui-MAIN:65: bad argument #3 to 'Position' (UDim2 expected, got number)

虽然这个错误似乎没有做任何事情。 (例如,完全停止脚本)

导致错误的行已用注释标记。

我已经确定 pos 是正确的。我什至尝试在设置之前打印它,它打印出正确的东西是: {0,120},{0,65}

另一个主要问题是我用了一次就恢复不了了。它可以 运行 这一行多次罚款:

coroutine.resume(playAnimation,"Cannon Fire",UDim2.new(0,120,0,68-25),tank.Frame)

但不会 运行:

if tank2:FindFirstChild("Ammo") and isTouching(ammoFrame,tank2:GetChildren()[3]) then
    local lastAmmoPos = ammoFrame.Position
    ammoFrame:Destroy()
    coroutine.resume(playAnimation,"Explosion",lastAmmoPos-UDim2.new(0,25-(ammoTypes[type]["Size"].X.Offset)/2,0,25),tank.Frame)
    tank2:GetChildren()[3]:Destroy()
end

是的,if 语句运行良好。 ammoFrame 被摧毁,tank2 的第三个 child 也被摧毁。协程不会恢复。

已通过完全删除协程并将 for 循环包装在 spawn 函数中进行修复。

local playAnimation = function(anim,pos,tank)
    local animBase = sp.AnimBase:Clone()
    animBase.Parent = tank
    animBase.Visible = true
    animBase.Position = pos
    local frame = 1
    spawn(function()
        for i = 0, animations[anim]["FrameNum"] do
            frame = frame + 1
            animBase.Image = animations[anim]["Frames"][frame]
            wait(.1) --this right here, the wait, interfears with the yield.
            if frame >= animations[anim]["FrameNum"] then
                break
            end
        end
        animBase:Destroy()
    end)
end