【问题标题】:Is it safe to start a new coroutine inside a current coroutine?在当前协程中启动新协程是否安全?
【发布时间】:2015-11-27 22:01:17
【问题描述】:

我有一个基于网格的游戏,我在其中编写了我的移动脚本来逐个单元格地移动我的游戏对象。为了实现我想要的逐个单元移动,我不得不使用协程。

这是我的代码的伪代码sn-p:

private Coroutine currentCoroutine;

public void Move(Vector3 velocity)
{
    currentCoroutine = StartCoroutine(MoveCoroutine(velocity));
}

private IEnumerator MoveCoroutine(Vector3 velocity)
{

    Vector3 endPoint;
    Vector3 nextVelocity;

    if(velocity == Vector3.Right)
    {
        endPoint = rightEndPoint;
        // object should move left in the next coroutine
        nextVelocity = Vector3.Left;
    }
    else
    {
        endPoint = leftEndPoint;
        // object should move right in the next coroutine
        nextVelocity = Vector3.Right;
    }

    while(currentPos != endPoint)
    {
        currentPos += velocity

        yield return new WaitForSeconds(movementDelay);
    }

    currentCoroutine = StartCoroutine(MoveCoroutine(nextVelocity));

}

基本上,它的作用是左右移动我的对象。如果它已经到达左边缘,我让它向右走,反之亦然。我从另一个脚本调用Move()

这段代码对我来说很好用。但是,我不确定在协程中启动一个新的协程是否安全,就像我在这里所做的那样。写这样的协程有什么后果吗?我还在习惯协程的概念。

谢谢

【问题讨论】:

    标签: unity3d coroutine


    【解决方案1】:

    在协程结束时启动一个新的协程是安全的。顺便说一句,我注意到您的 yield 语句仅在 while 循环内调用。如果 while 循环有可能至少不会运行一次,那么您将遇到错误;所有协程都必须执行一个 yield 语句。

    【讨论】:

    • 感谢您解决这个问题。至于我在while循环中的yield语句,我需要里面的yield来实现一个单元一个单元的移动。我确保 while 循环不会至少运行一次。但是有没有一种方法可以让我将收益放在循环之外并仍然实现我想要的运动?
    • 你可以有多个 yield 语句。使用您现有的代码,您可以将 yield return null; 放在它总是被调用的地方。
    • 啊,我明白了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2020-04-12
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多