如何循环协程

问题描述 投票:0回答:1

我正在编写一个 2d 游戏,我想在其中制作打开和关闭的火炬的动画。我有一个火炬打开的动画和一个火炬关闭的动画。它应该在无限循环中打开 3 秒并关闭另外 3 秒。 这是代码:

Animator anim;

void Start()
{
    anim = GetComponent\<Animator\>();
    StartCoroutine(waitSeconds());
}  

IEnumerator waitSeconds()
{  
    while(true)
    {
        anim.Play("firetorchon-Animation");
        yield return new WaitForSeconds(3);
        anim.Play("firetorchoff-Animation");
        yield return new WaitForSeconds(3);
    }
}

while 循环不起作用 - 只显示关闭的动画,并且永远不会转换为打开状态,我怎样才能以另一种方式实现这一点?

unity-game-engine game-development unityscript
1个回答
0
投票

您可以使用

InvokeRepeating()
来调用调用协程的函数。这可能不是最好的方法,但它是最简单、最快的。

Animator anim;

private void Start()
{
    anim = GetComponent<Animator>();
    InvokeRepeating(nameof(AnimateTorch), 0f, 0f);
}

private void AnimateTorch()
{
    StartCoroutine(waitSeconds());
}

IEnumerator waitSeconds()
{
    anim.Play("firetorchon-Animation");
    yield return new WaitForSeconds(3);
    anim.Play("firetorchoff-Animation");
    yield return new WaitForSeconds(3);
}

如果代码不起作用,那么您可能需要确保动画正确完成。

© www.soinside.com 2019 - 2024. All rights reserved.