微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

循环等待操作完成

我在Unity3d中工作(这更多是C#问题,所以我怀疑这是一个问题).我正在研究《文明》中的运动系统.我有一个循环设置,以便您每转可以移动2个正方形.这很好.我在10个街区外的正方形上单击,然后花5个转弯才能到达.现在,我正在尝试使棋子在块之间缩.我有lerp可以工作,问题是,它从当前图块跳到第一个图块,然后过渡到应该位于的第2个图块.我使用协程代替更新功能来完成这项工作(因为更新将使它只停留在最终目的地,而不是从当前到第一,第二).因此,我遇到的是典当所经历的每一个动作所经过的循环,在继续自己的循环之前,不等待协程完成.这是代码

public void MoveNextTile()
{
    float remainingMoves = moveSpeed;
    while (remainingMoves > 0)
    {

        if (currentPath == null)
            return;
        //Get the cost from current tile to next tile
        remainingMoves -= map.CostToEnterTile(currentPath[0].x, currentPath[0].y, currentPath[1].x, currentPath[1].y);

        //Move us to the next tile in the sequence
        toVector = map.TileCoordToWorldCoord(currentPath[1].x, currentPath[1].y);
        Vector3 fromVec = transform.position;
        StartCoroutine(MoveObject(fromVec, toVector, 1.0f));


        //transform.position = map.TileCoordToWorldCoord(currentPath[1].x, currentPath[1].y);

        //Remove the old current tile

        this.tileX = currentPath[0].x;
        this.tileY = currentPath[0].y;
        currentPath.RemoveAt(0);
        if (currentPath.Count == 1)
        {
            this.tileX = currentPath[0].x;
            this.tileY = currentPath[0].y;
            currentPath = null;
        }


    }

}
IEnumerator MoveObject(Vector3 source, Vector3 target, float overTime)
{
    float startTime = Time.time;
    while (Time.time < startTime + overTime)
    {
        transform.position = Vector3.Lerp(source, target, (Time.time - startTime) / overTime);
        yield return null;
    }
    transform.position = target;

}

我知道这是一个菜鸟问题.我只是从来不需要在C#中执行此操作.预先感谢所有帮助

解决方法:

我建议您研究协程的工作方式.

您的协程没有完全执行,然后返回以完成其余的MoveNextTile函数.它实际上一直执行到第一个yield语句,然后继续执行MoveNextTile.每个后续框架将继续运行协程的一个“步骤”,直到下一个yield语句,以尝试复制异步方法.

您想要做的就是告诉您的程序明确等待协程完成.这样做;

收益回报StartCoroutine(MoveObject(fromVec,toVector,1.0f));

当然,您只能在IEnumerator中使用此语句.因此,您必须将void MoveNextTile函数更改为IEnumerator MoveNextTile.您最终得到如下结果;

public IEnumerator MoveNextTile() {

    // Ommited
    while (remainingMoves > 0) {
        //Ommited
        yield return StartCoroutine(MoveObject(fromVec, toVector, 1.0f));
        // Now MoveNextTile will continue after your MoveObject coroutine finishes.
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐